Haskell: simple way to read a line containing Int and Float?
haskell
Solution
One neat way to express this is using the `ViewPatterns` extension
{-# LANGUAGE ViewPatterns #-}
readFoo :: String -> (Int, Float)
readFoo (words -> [read -> i, read -> f]) = (i ,f)
Another way to write it in standard Haskell would be e.g.
readFoo :: String -> (Int, Float)
readFoo ln = (read i, read f) where
[i, f] = words ln
Of course, all this assumes that you don't care about error handling.
Problem
I want to read lines from a file that looks like this: ``` 1 2.1 2 2.2 3 2.3 ``` It's a simple an Int and a Float on each line This is what I came up with, to read each line: ``` readFoo :: String -> (Int, Float) readFoo line = (read (splitOn " " line !! 0), read (splitOn " " line !! 1)) ``` Or I also made a datatype, and then the `read` part is simple. ``` data Foo = Foo Int Float deriving (Show, Read) getM (Foo m p) = m getP (Foo m p) = p readFoo :: String -> Foo readFoo line = read $ "Foo " ++ line :: Foo ``` But there must be a simpler way to do this, right?