0

Lets say I have a file

8 [[1,2,3,4],[1,2]]

with number and list of lists in it.

This code allow me to read all line or n-th element from it.

import System.IO

main = do
      x <- openFile "file.txt" ReadMode
      cont <- hGetContents x
      let fLines = lines cont
      let numb = fLines !! 0 !! 0
      print numb

here numb is '8'.

How can I get integer 8 from numb without using other libraries?

And is there a possibility to read list of lists and use it as list of lists?

Or should I better write each list in a new row, and read them row by row and add to empty list?

Maybe it's a stupid question, but I didn't find any example of doing something like that on internet.

UPDATE

Thanks to Fractal answer I've managed to write this

rList :: String -> [[Int]]    
rList = read

which is working for list of lists!

However, when I cant make it work with single Int.

into :: String -> Int
into = read

Don't know why, but it doesn't work for numb T_T

UPDATE 2

Ok, it was kinda stupid. numb is Char here, so to make it work it will be enough to write

print (into [numb])

Thank you all for answers.

2
  • Is the index always going to be a one-digit number? You would probably be better served by looking for the first space, in that example. Commented Jan 22, 2016 at 21:58
  • 1
    Rather than indexing into flines with !!, it might be better to split at whitespace with words. That way it is more flexible, and you won't have to convert the leading Char back to a String. Commented Jan 23, 2016 at 11:40

2 Answers 2

1

You can use read to parse String representations of Haskell data structures. This should work for your list of lists as well.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the ord function :: Char -> Int

That function could be found searching for the Char -> Int type signature on the Hoogle search engine: http://hoogle.haskell.org/?hoogle=Char+-%3E+Int

Documentation: https://hackage.haskell.org/package/base/docs/Data-Char.html#v:ord

Example:

import System.IO
import Data.Char (ord)

main = do x <- openFile "file.txt" ReadMode
          cont <- hGetContents x
          let fLines = lines cont
          let numb = fLines !! 0 !! 0
          let numbInt = ord numb - ord '0'
          print numbInt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.