haskell列表语法中的冒号与括号 [英] Colon versus brackets in haskell list syntax

查看:722
本文介绍了haskell列表语法中的冒号与括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习haskell,然后我来到这个练习中,我必须定义一个函数来获取数字列表的结果。我被提供了选择,并且因为我是哈斯克尔的新手,所以有一些符号我有点不清楚。



所以我在其中一个选择中看到了这个定义:

  p [x,xs] = x * product xs 

我可以理解这一点,它意味着以获得列表的产品,然后乘以x的值。

然后我看到另一个选择的其他定义:

  p(x:xs)= x * product xs 

我完全不明白。它使用括号和冒号,我很难找到它们的定义。

解决方案

[x,xs]如果有人能够启发我的语法和语义, 是一个包含两个元素的列表。第一个元素称为 x ,第二个元素称为 xs 。因此,在这种情况下, product xs 不会计算列表的乘积,它会计算第二个元素的乘积。由于列表中的元素不能是列表本身(否则与x相乘将不起作用),这是一种类型错误。



x:xs 是一个包含至少一个元素的列表。它的第一个元素称为 x ,包含其剩余元素的列表称为 xs


I'm currently learning haskell then I came to this exercise where I have to define a function that gets the product of a list of numbers. I was provided with choices and since I am new to haskell there are some notations that I am a bit unclear of.

So I saw this definition on one of the choices:

p [x, xs] = x * product xs

I can understand this quite a bit, it means to get the product of the list and then multiply it with the value of x.

Then I saw this other definition on one of the other choice:

p (x : xs) = x * product xs

Which I totally do not understand. It uses parenthesis and a colon which I am having a hard time looking for their definition. I appreciate if someone could enlighten me with regards the syntax and semantics.

解决方案

[x, xs] is a list containing two elements. The first element is called x and the second is called xs. So in this case product xs does not calculate the product of the list, it calculates the product of the second element. Since the elements of the list can't be lists themselves (or else multiplying with x wouldn't work), this is a type error.

x : xs is a list that contains at least one element. Its first element is called x and the list containing its remaining elements is called xs.

这篇关于haskell列表语法中的冒号与括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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