I have a String like "1 2 3 4 5". How can I convert it into a list of integers like [1,2,3,4,5] in Haskell? What if the list is "12345"?
Is a string a list of char Haskell? A String is a list of characters. String constants in Haskell are values of type String .
What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range. The language standard only guarantees a range of -229 to (229 - 1).
In Haskell a String is just a list of Char s, indeed type String = [Char] . String is just an "alias" for such list. So all functions you define on lists work on strings, given the elements of that list are Char s.
You can use:
> [read [x] :: Int | x <- string]
You can use
Prelude> map read $ words "1 2 3 4 5" :: [Int]
[1,2,3,4,5]
Here we use words to split "1 2 3 4 5" on whitespace so that we get ["1", "2", "3", "4", "5"]. The read function can now convert the individual strings into integers. It has type Read a => String -> a so it can actually convert to anything in the Read type class, and that includes Int. It is because of the type variable in the return type that we need to specify the type above.
For the string without spaces, we need to convert each Char into a single-element list. This can be done by applying (:"") to it — a String is just a list of Chars. We then apply read again like before:
Prelude> map (read . (:"")) "12345" :: [Int]
[1,2,3,4,5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With