如何纠正语法分析错误?

huangapple go评论59阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2020年1月7日 02:42:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/59617317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定