ruubel
ruubel

Reputation: 153

Haskell Parse string of Ints to tuple (Int,Int)

I would like to parse a string in form 3 3 from input user to a tuple (3,3) is this possible?

stringtup :: String -> Maybe (Int, Int)
stringtup s = do
[(n, [c])] <- return $ reads s
return (n, c)

this is my attempt but it does't work..

Upvotes: 1

Views: 713

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120711

reads only parses one value (if possible), and gives it back as well as the rest of the input string. So,

    [(n, _)] <- return $ reads s

works and will, for "3 3" indeed have n≡3.

But the other number still needs to be parsed too. So what you'd actually do is first bind something like

    [(n, s')] <- return $ reads s

and then parse the other number in the same fashion from s'.

Upvotes: 2

Related Questions