Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell readLn no parse error

This function allows the user to input a list of strings. The function takes the length and allows the user to input length-1 more lines. Then each line is checked to ensure it is the same length as the original line. The code:

readme :: IO [Line]
readme = do
 line <- readLn
 let count = length line
 lines <- replicateM (count-1) $ do 
  line <- readLn
  if length line /= count 
  then fail "too long or too short"
  else return line 
 return $ line : lines

Line is of type String.

When I try to run the function and input.. say ["12","13"] I get the following: * Exception: user error (Prelude.readIO: no parse) and I can't figure out why, any ideas?

like image 509
gdrules Avatar asked Mar 12 '12 12:03

gdrules


2 Answers

If it's any help, your program accepts the following input:

*Main> readme
"abc"
"123"
"456"
["abc","123","456"]

You might have intended to write getLine instead of readLn, but without knowing the purpose of your program this is a bit hard to tell.

Changing to getLine, the program accepts:

*Main> readme
abc
123
456
["abc","123","456"]
like image 110
Deestan Avatar answered Oct 09 '22 15:10

Deestan


It's because you are trying to read something with the wrong type.

You say that Line is a String aka. [Char]. However, the input you are typing is of the format ["12", "13"] which looks like it should have type [Line], aka. [String] or [[Char]].

You need to explain what a Line is actually supposed to be. If you want a Line to be a string, then why are you entering lists of strings at the terminal? Something is wrong with your logic in this case.

If you want a method for inputting square matrices, you can let type Line = [Int] instead, and use one of these formats:

-- What you type at the terminal:
1 -2 3
4 5 6
6 7 8

-- How to read it in your program:
line <- (map read . words) `fmap` getLine

-- What you type at the terminal:
[1, -2, 3]
[4, 5, 6]
[6, 7, 8]

-- How to read it in your program:
line <- readLn

If you really want to input lines, so that type Line = [Char], and that each number in the input list becomes a unicode character, meaning that when you enter [97, 98, 99] on the terminal, you get the string "abc":

-- What you type at the terminal:
[97, 98, 99]
[100, 101, 102]
[103, 104, 105]

-- How to read it in your program:
line <- (map toEnum) `fmap` readLn
like image 41
dflemstr Avatar answered Oct 09 '22 15:10

dflemstr