Haskell函数中的括号 [英] parenthesis in Haskell functions

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

问题描述

我只想知道我们如何知道哪些函数需要使用方括号(),而哪些不需要?例如

I just want to know how do we know which functions need brackets () and which ones do not? For example

replicate 100 (product (map (*3) (zipWith max [1,2,3,4,5] [4,5,6,7,8])))

正常工作.但是

replicate 100 (product (map (*3) (zipWith (max [1,2,3,4,5] [4,5,6,7,8]))))

不起作用.这是因为我为zipWith放置了一组括号.在这个小例子中,zipWith和max没有括号,但是复制,乘积和映射却有.通常,有一种方法可以知道/弄清楚哪些功能需要使用括号,哪些不需要.

does not work. It is because I put a set of brackets for zipWith. In this small example, zipWith and max do not have brackets, but replicate, product and map do. In general is there a way to know/figure out which functions need brackets and which ones dont.

推荐答案

功能应用程序保持关联性.因此,当您编写类似以下内容的表达式时:

Function application is left associative. So, when you write an expression like:

f g h x

它的意思是:

((f g) h) x

zipWith的类型也提供了一个线索:

And also the type of zipWith provides a clue:

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

它表示zipWith具有3个参数:一个函数和两个列表.

it says that zipWith has 3 parameters: a function and two lists.

撰写时:

zipWith (max [1,2,3,4,5] [4,5,6,7,8])

口译员会理解

max [1,2,3,4,5] [4,5,6,7,8]

将是zipWith的第一个参数,其类型不正确.请注意,zipWith期望将两个自变量作为第一个自变量,如@Cubic所指出,max [1,2,3,4,5] [4,5,6,7,8]将返回最大值. 在这两个列表之间,按照通常的字典顺序(对于某些类型为OrdNum的实例a),该类型将为[a].就是说,由于您尝试传递类型的值,该错误变得明显

will be the first parameter to zipWith, which is type incorrect. Note that zipWith expects a function of two arguments as its first argument and, as pointed out by @Cubic, max [1,2,3,4,5] [4,5,6,7,8] will return the maximum between these two lists according the usual lexicographic order, which will be of type [a], for some type a which is instance of Ord and Num. Said that, the error become evident since you are trying to pass a value of type

(Num a, Ord a) => [a]

其中的值类型

(a -> b -> c)

是预期的.

这篇关于Haskell函数中的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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