Haskell string to list

25,693

Solution 1

Use intersperse

myShow :: String -> String
myShow s = concat ["[", intersperse ',' s, "]"]

Solution 2

import Data.Char (digitToInt)

map digitToInt "12345"

Solution 3

You should map the function read x::Int to each of the elements of the string as a list of chars:

map (\x -> read [x]::Int) "1234"

If you have non-digit characters you should filter it first like this:

import Data.Char
map (\x -> read [x]::Int) (filter (\x -> isDigit x) "1234##56")

That results in:

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

Solution 4

Have you taken a look at this answer? Convert string list to int list

A String is just a list of characters in Haskell after all. :)

Solution 5

Try using splitEvery with length 1

Share:
25,693
thetux4
Author by

thetux4

Updated on March 31, 2020

Comments

  • thetux4
    thetux4 about 4 years

    Possible Duplicate:
    convert string list to int list in haskell

    I have a string 12345. How can I show it in list form like [1,2,3,4,5]? And also what if i have a string like ##%%? I can't convert it to Int. How can view it in the form [#,#,%,%]?

  • thetux4
    thetux4 about 13 years
    This works but what if i have a string like "##%%" ?
  • Santiago Alessandri
    Santiago Alessandri about 13 years
    This counts that the string is made up by digits. If you want to filter the characters that are not digits you should use a filter. I will edit the answer
  • thetux4
    thetux4 about 13 years
    I changed my question as well. Actually i don't want to split nondigits. I want to view them in list form.
  • thetux4
    thetux4 about 13 years
    I checked it but when i try to convert a string like "&%" it gives parse error.