1

First of all, sorry for my bad english. I'm not native and try my best :)

Now to the problem: i have a list of Strings and want to convert them to a list of integers. The Problem is, it's not just numbers, basically the String is a List to.

["[1,2,3,4,5,6,7,8]","[8,7,6,5,4,3,2,1]","[1,2,3,4,5,6,7,8]"]

This is the result i get from my code i'll post further down.

Any idea how i can achieve, that the internal list of numbers are list of integers? I tried like three hours and didn't find a solution.

Every help is appreciatet.

Kind regards

get "/authors/:author" $ do
     authorName <- param "author"
     directories <- liftIO(listDirectory("data/" ++ authorName))
     liftIO(readFiles directories authorName)
     html (T.pack (HtmlModule.h1 ("Author: " ++ authorName)))


readFiles :: [String] -> String -> IO ()
readFiles x authorName = do
  let y =  addPrefix x authorName
  content <- mapM readFile y
  putStrLn (show content)

Result: ["[1,2,3,4,5,6,7,8]","[8,7,6,5,4,3,2,1]","[1,2,3,4,5,6,7,8]"]

2 Answers 2

6

You can read the string into a list of ints:

let nums = map read content :: [[Int]]
Sign up to request clarification or add additional context in comments.

1 Comment

If i could i would marry you! Thank you so much. I tried this approach simillarly but it didn't work. Your solution works like a charm. Thank you so much!!
3

You can use read :: Read a => String -> a to convert a string to a type that is a member of the Read typeclass.

Since Int is a member of the Read typeclass, and [a] is a member of the Read typeclass if a is a member of the Read typeclass, we thus can read a list of Ints:

Prelude> read "[1,2,3,4,5,6,7,8]" :: [Int]
[1,2,3,4,5,6,7,8]

We thus can convert a list of Strings with:

    content <- mapM ((read :: String -> [Int]) . readFile) y

read will raise an error in case the String can not be converted. You can make use of readMaybe :: Read a => String -> Maybe a to wrap the result in a Just in case parsing was successful, and Nothing in case parsing failed.

2 Comments

Same to you. Thank you so much for your help. It is much appreciated!
To get a "Maybe" value if a read fails, use traverse: traverse (readMaybe @[Int]) which has the type Traversable t => t String -> Maybe (t [Int]). @[Int] is an example of visible -XTypeApplications. I prefer writing, say read @[Int] <$> content, to read <$> content :: [[Int]]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.