英文:
How to correct syntactical parsing error?
问题
我正在编写一个作为示例的扩展的Car数据类型:data Car = Car{customers::[a]}
其中customers::[a]
用于显示乘坐汽车的客户列表。然后,我编写了一个名为ListCustomer
的函数,用于将数据集中的数据转换为列表并存储所有客户的列表。
我已经编写了:
ListCustomer::Car->[a]
ListCustomer (Car{customers = [a]}) = [a]
括号中出现了解析错误。我已经检查了括号,它们似乎是平衡的。
英文:
I'm writing a Car data type as an extension to an example: data Car = Car{customers::[a]}
where customers::[a]
is to show a list of customers who are riding the car. Then I have written a function of ListCustomer
to store a list of all customers by converting the data from data set into a list.
I have written :
ListCustomer::Car->[a]
ListCustomer (Car{customers = [a]}) = [a]
and there is parsing error in the brackets. I have checked the brackets and they appear balanced.
答案1
得分: 1
编译器的提示是它不理解你声明的函数,因为在Haskell中,函数必须以小写字母开头。这个可以编译通过:
listCustomer :: Car a -> [a]
listCustomer (Car{customers = [a]}) = [a]
我应该补充说明,如果你使用像Car [1,2]
或Car []
这样的输入,它会抛出一个"非穷尽模式"错误,因为Haskell将模式customers = [a]
解释为"customers字段中的一个元素的列表"。纠正这个问题的一种方法是从函数中简单地移除括号:
listCustomer (Car{customers = a}) = a
现在,a
只是代表"customer字段中的任何东西"。请注意,你的listCustomer
函数是多余的,因为记录语法已经为你提供了customers
字段的获取器:
> customers $ Car [1,2]
> [1,2]
英文:
What the compiler is telling you is that it doesn't understand the function you're declaring, since functions in Haskell have to start with a lower case letter. This compiles:
listCustomer :: Car a -> [a]
listCustomer (Car{customers = [a]}) = [a]
I should add that this will throw a "non-exhaustive pattern" error if you use it with inputs like Car [1,2]
or Car []
, since Haskell interprets the pattern customers = [a]
as "a list of one element in the customers field". One way to correct this is to simply remove the brackets from your function:
listCustomer (Car{customers = a}) = a
Now, a
simply stands for "anything in the customer
field". Note that your listCustomer
function is redundant, since the record syntax already provides you with a getter for the customers
field:
> customers $ Car [1,2]
> [1,2]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论