Alex
Alex

Reputation: 667

Read strings as ints haskell

is there anyway I could read a string as an integer?

For example reading

triangle = ["1"
           ,"2 3"
           ,"4 5 6"]

as [[1],[2,3],[4,5,6]]

convertToInt :: [String] -> [[Int]]
convertToInt [] = []
convertToInt (x:xs) = **(somehow convert x to list of ints)** : convertToInt xs

Not sure how to procede, are there any inbuilt functions for this?

edit: thanks! This is the solution

convertToInt :: [String] -> [[Int]]
convertToInt [] = []
convertToInt (x:xs) = (map read (words x)) : convertToInt xs

Upvotes: 1

Views: 105

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 47402

Here's a hint to get you started

>> let str = "1 2 3"
>> words str
["1","2","3"]
>> map read (words str) :: [Int]
[1,2,3]

Edit

Since you've now figured what you need to do, I wanted to show you another solution, that might get you thinking a bit more about Haskell

convertToInt :: [String] -> [[Int]]
convertToInt = map (map read . words)

Try and figure out how it works - your understanding of Haskell will improve dramatically.

Upvotes: 7

Related Questions