将字符串(从文件)转换为元组时混沌 [英] Chaos while converting Strings (from files) to Tuple

查看:112
本文介绍了将字符串(从文件)转换为元组时混沌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将两个文本文件转换为字符串,然后将它们以双元组的形式添加到列表中。像这样: [(_,_),(_,_)]
这是我的功能:

  testa = do 
questions< - readFilequestionsQ.txt
category< - readFilecategory.txt
print(myZip类别(行问题))

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

questions.txt 包含每行一个问题



categories.txt 包含一行长度为50的数字,每个代表5个类别之一

(注意–它可能在Mac电脑上工作,但我不知道为什么)
这是我的错误当我尝试运行该程序时(至少有一些):

  [(0,I prefer variety (0,),(0,我是一个具有生动想象力的创新人物),(0,),(0,我喜欢狂放的幻想飞行).... 
ghci>
***例外:todo.hs:(35,1) - (37,44):函数myZip中的非穷举模式

为什么它将空字符串组合起来?为什么会出现错误信息?

解决方案

例外!怎么可能?

这不是一个讽刺。

但是有一条消息告诉你,

a非穷举模式

在这件事上

被发现在你的 myZip 中。






您错过了以下案例的模式:

  myZip [] [1] = ??? 

如果您使用过 -Wall ,则编译器会给出以下警告:

 
Code.hs:2:1:警告:
模式匹配非穷举
在'myZip'的等式中:模式不匹配:[](_:_)

如果您的函数将为几乎所有的模式返回相同的值,除了一个之外,通常先定义一个然后匹配其他所有模式通常会更容易:

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

这样你不会错过一个模式。


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?

解决方案

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.

这篇关于将字符串(从文件)转换为元组时混沌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆