Haskell readLn no parsing error

This function allows the user to enter a list of strings. The function takes a length and allows the user to enter another 1 line in length. Then each line is checked to make sure that it has 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 

A string is of type String.

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

+6
source share
3 answers

This is because you are trying to read something with the wrong type.

You say that Line is a String aka. [Char] . However, the input you enter has the format ["12", "13"] , which looks as if it should be of type [Line] , otherwise. [String] or [[Char]] .

You need to explain what Line should be. If you want the Line line to be a line, then why do you enter lists of lines in the terminal? Something is wrong with your logic in this case.

If you want to use the square matrix input method, you can enable one of the following formats instead of type Line = [Int] :

 -- 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 enter lines, so that type Line = [Char] and that every number in the input list becomes a Unicode character, which means that when you enter [97, 98, 99] on the terminal, you will 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 
+7
source

If this helps, your program accepts the following input:

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

Perhaps you intended to write getLine instead of readLn , but without knowing the purpose of your program, it is a little difficult to say.

Switching to getLine , the program accepts:

 *Main> readme abc 123 456 ["abc","123","456"] 
+4
source

read not very user friendly and does not see ["12","13"] as a string. It will accept "123" or ['1','2','3'] or even "[\"12\",\"13\"]" - in other words, the line should be written as it would in your program. In this case, you do not need to use read because you are just reading String , so replacing readLn with getLine will work.

+4
source

Source: https://habr.com/ru/post/910500/


All Articles