Chaos while converting Strings (from files) to Tuple

笑着哭i 提交于 2019-12-13 07:46:06

问题


I'm trying to convert two textfiles into strings, and then adding them together in double-tuples, in a list. like this: [(_,_),(_,_)] This is my function:

testa = do  
    questions <- readFile "questionsQ.txt" 
    category <- readFile "category.txt"
    print (myZip category (lines questions))

myZip :: [a] -> [b] -> [(a, b)]
myZip [] [] = []
myZip _ [] = []
myZip (x:xs) (y:ys) = [(x,y)] ++ myZip xs ys

questions.txt contains one question per row

categories.txt contains a line of 50 numbers in a long row, each one representing one of the 5 categories

(Note – it may work at Mac computers, but I don't know why) This is my error message when I try to run the program (some of it at least):

[("0","I prefer variety to routine"),("0",""),("0","I'm an innovative person with a vivid imagination"),("0",""),("0","I enjoy wild flights of fantasy")....
ghci>
*** Exception: todo.hs:(35,1)-(37,44): Non-exhaustive patterns in function myZip

Why does it combine tuples with empty strings? And why is an error message occuring?


回答1:


An exception! How can that be?
Isn't that quite a quip.
But there's a message, telling ye,
a non-exhaustive pattern
in this very matter
was found in your myZip.


You're missing the pattern for the following case:

myZip [] [1] = ???

If you had used -Wall, the compiler would have given the following warning:

Code.hs:2:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for `myZip': Patterns not matched: [] (_ : _)

If your function is going to return the same value for almost all patterns except one, it's often easier to define that one first and then match all others:

myZip (x:xs) (y:ys) = [(x,y)] ++ myZip xs ys
myZip _      _      = []

That way you don't miss a pattern by accident too.



来源:https://stackoverflow.com/questions/35731286/chaos-while-converting-strings-from-files-to-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!