[Haskell-begin] Using read, reads...
Felipe Lessa
felipe.lessa at gmail.com
Mon Jul 21 00:51:27 EDT 2008
On Sun, Jul 20, 2008 at 10:30 PM, Rafael Gustavo da Cunha Pereira
Pinto <rafaelgcpp at gmail.com> wrote:
>
> -------------sample.in-------------
> 01 02 03 04 05 06
> 10 11 15 18 29 45
> 19 22 10 01 23 14
> -----------------------------------------
>
So, you got something like "10 11 15 18 29 45". So, we may want first
to separate them into ["10", "11", "15", "18", "29", "45"]. Having
this list, we simply apply read, constrained to String -> Int, to all
its members, so we obtain [10, 11, 15, 18, 29, 45] :: [Int]. Now,
translating what I said to Haskell:
convert :: String -> [Int]
convert = map read . words
read :: FilePath -> IO [[Int]]
read fp = (map convert . lines) `fmap` readFile fp
(I've taken some "shortcuts" in the code above because that's how I'd
write it. If you have trouble to understand it on a first glance, try
to read carefully the docs of each function and mentally execute an
example.)
HTH,
--
Felipe.
More information about the Beginners
mailing list