本文介绍了模式匹配时括号表示什么(x:xs)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用x:xs语法拆分列表时,为什么要用圆括号包装?括号的意义是什么?为什么不是[x:xs]或者只是x:xs?

解决方案

上下文,但在大多数情况下,这是因为

函数应用程序的绑定比任何中缀运算符都要紧。





例子:

 长度[] = 0 
长度(x:xs)= 1 +长度xs

被忽略了,编译器会认为你有一个参数 x ,然后是一个不合适的中缀运算符,它会怨声载道。另一方面,这是OK

 长度l = []的情况l  - > 0 
x:xs - > 1 +长度xs

在这种情况下, x xs 可能会被解释为函数应用程序的一部分,所以不需要使用圆括号。



请注意,同样美妙的规则函数应用程序绑定比任何中缀运算符更紧密可以让我们在 1 + length xs中编写 length xs 没有任何括号。中缀规则给予和中缀规则带走。


when you split a list using x:xs syntax why is it wrapped in a parentheses? what is the significance of the parentheses? why not [x:xs] or just x:xs?

解决方案

The cons cell doesn't have to be parenthesized in every context, but in most contexts it is because

Function application binds tighter than any infix operator.

Burn this into your brain in letters of fire.

Example:

length [] = 0
length (x:xs) = 1 + length xs

If parentheses were omitted the compiler would think you had an argument x followed by an ill-placed infix operator, and it would complain bitterly. On the other hand this is OK

length l = case l of [] -> 0
                     x:xs -> 1 + length xs

In this case neither x nor xs can possibly be construed as part of a function application so no parentheses are needed.

Note that the same wonderful rule function application binds tighter than any infix operator is what allows us to write length xs in 1 + length xs without any parentheses. The infix rule giveth and the infix rule taketh away.

这篇关于模式匹配时括号表示什么(x:xs)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:40