简体   繁体   English

haskell类型签名问题

[英]haskell type signature question

Can someone explain me, why do these functions have different number of arguments and behavior , but the same type signature , yet they are both correct? 有人可以解释一下,为什么这些函数具有不同数量的参数和行为 ,但是具有相同的类型签名 ,但是它们都是正确的?

comp1 :: (a -> b) -> (b -> c) -> a -> c
comp1 f g = g.f

comp2 :: (a -> b) -> (b -> c) -> a -> c
comp2 f g x = g (f x)

also, why does comp2 has 还有,为什么comp2有

comp2 :: (a -> b) -> (b -> c) -> a -> c

instead of something like 而不是像

comp2 :: a -> (a -> b) -> (b -> c) -> a -> c

?

Thank you. 谢谢。

comp1 fg = gf is written in point-free style (not referring to points, but to values ). comp1 fg = gf以无样式编写(不是指点 ,而是指 )。 When you call comp1 , there is implicitly a third parameter being passed to gf , which is the composition of the two functions g and f : (gf) x equals g (fx) , ie g is passed the result of fx . 当您调用comp1 ,隐式地将第三个参数传递给gf ,这是两个函数gf(gf) x等于g (fx) ,即g传递了fx的结果。 No parameter x exists in comp1 because it's implicitly passed to the function. comp1不存在任何参数x ,因为它已隐式传递给函数。 (You could think of comp1 as a partially applied or curried function if it makes you feel better.) (如果使您感觉更好,您可以将comp1视为部分应用咖喱函数。)

comp2 's type asks for two functions, one from (a->b) and another (b->c) , as well as a parameter of type a . comp2的类型询问两个功能,一是从(a->b)和另一个(b->c)以及一个类型的参数a There is no need to put an a -> in its signature. 无需在其签名中添加a ->

The two functions are really equivalent; 这两个功能实际上是等效的。 one simply uses some Haskell tricks to be more concise. 一个人只是简单地使用一些Haskell技巧就更简洁了。

comp2 f g x = g (f x)

is syntactic sugar for 是语法糖

comp2 = \f -> \g -> \x -> g (f x)

Similarly 相似地

comp1 f g = g.f

is sugar for 是糖

comp1 = \f -> \g -> g.f

The definition of . 的定义. is: 是:

f1 . f2 = \x -> f1 (f2 x) -- Names of arguments have been changed to avoid confusion

So if we insert the definition into the desugared form of comp1 , we get: 因此,如果将定义插入到comp1的简化格式中, comp1得到:

comp1 = \f -> \g -> \x -> g (f x)

This is exactly the same as the desugared form of comp2 , so clearly the definitions are equivalent. 这与comp2的简化形式comp2 ,因此显然定义是等效的。

Currying . 咖喱 A multi-argument function in ML and Haskell, is just syntactic sugar for a one-argument function that returns a function; ML和Haskell中的多参数函数只是返回一个函数的单参数函数的语法糖。 the function that it returns takes the remaining arguments. 它返回的函数采用其余参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM