简体   繁体   English

在Haskell中键入函数的签名

[英]Type signature of functions in Haskell

I have defined three functions in haskell which multiply two numbers 我在haskell中定义了三个函数,它们将两个数相乘

k = \x y -> x * y

foo y = \x -> x * y

bar x = \x -> x * x

But I am getting different signatures for all the three functions. 但是我为这三个功能获得了不同的签名。

λ> :t k
k :: Integer -> Integer -> Integer
λ> :t foo
foo :: Num a => a -> a -> a
λ> :t bar
bar :: Num a => t -> a -> a

Can somebody explain why it is so? 有人可以解释为什么会这样吗? I can see t in type signature of bar. 我可以在酒吧的类型签名中看到。 is it different from normal usage of a, b, or a1, a2 etc 它是否与a,b或a1,a2等的正常使用不同

First of: all the signatures basically come from (*) :: Num a => a -> a -> a and your usage of it. 第一个:所有的签名基本上来自(*) :: Num a => a -> a -> a以及你对它的使用。 And yes k and foo should be the same but bar is indeed a bit different as you wrote it here. 是的, kfoo应该是一样的但是bar确实有点不同,就像你在这里写的那样。

  • foo should be obvious (I hope) (it's just that * is polymorphic and the type says just that) foo应该是显而易见的(我希望)(只是*是多态的,类型只是说)
  • for bar it's because the x on the left side is not used on the right side so you get the extra parameter t - it's the same as bar y = \\x -> x * x bar ,那是因为在x左侧上没有使用right一边让你获得额外的参数t -这是同bar y = \\x -> x * x
  • for k see the Monomorphism restriction - basically Haskell will pull a default-type here to work around some slight problems that could arise. 对于k请参阅Monomorphism限制 - 基本上Haskell将在此处提取默认类型以解决可能出现的一些轻微问题。 It's a bit strange that you get it here because by default newer GHCi version should not show this behavior (see the link) 你在这里得到它有点奇怪,因为默认情况下较新的GHCi版本不应该显示这种行为(参见链接)

btw: don't wonder to much about the names of the types ;) 顺便说一句:不要太在意这些类型的名字;)

The lesson learned should probably be to just write down your signatures (at least on top-level functions) ^^ - it would have solved all your problems 所吸取的教训应该是写下您的签名(至少在顶级函数上)^^ - 它会解决您的所有问题

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

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