Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i convert String into list of integers in Haskell

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"?

like image 995
Rog Matthews Avatar asked Jan 16 '12 11:01

Rog Matthews


People also ask

Is a string a list in Haskell?

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 is the difference between Int and integer in Haskell?

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).

How do you use strings in Haskell?

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.


2 Answers

You can use:

> [read [x] :: Int | x <- string]
like image 85
Wrichik1999 Avatar answered Oct 07 '22 20:10

Wrichik1999


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]
like image 24
Martin Geisler Avatar answered Oct 07 '22 18:10

Martin Geisler