[英]Simplify Haskell Type Signatures
My question is about how to work with Haskell type signatures analytically. 我的问题是如何分析处理Haskell类型签名。 To make it concrete, I'm looking at the "fix" function:
为了使它具体化,我正在寻找“修复”功能:
fix :: (a -> a) -> a
and a little made-up function that I wrote to do Peano-ish addition: 还有一个小编的功能,我写的做Peano-ish的补充:
add = \rec a b -> if a == 0 then b else rec (a-1) (b+1)
When I examine the types, I get my expected type for fix add
: 当我检查类型时,我得到了我想要的
fix add
类型:
fix add :: Integer -> Integer -> Integer
And it seems to work like I'd expect: 它似乎像我期望的那样工作:
> (fix add) 1 1
2
How can I work with the type signatures for fix
and for add
to show that fix add
has the above signature? 如何使用类型签名进行
fix
和add
以显示fix add
具有上述签名? What are the "algebraic", if that's even the right word, rules for working with type signatures? 什么是“代数”,如果这是正确的词,使用类型签名的规则? How could I "show my work"?
我怎么能“展示我的作品”?
ghci
tells us ghci
告诉我们
add :: Num a => (a -> a -> a) -> a -> a -> a
modulo some typeclass noise since the second argument to add
requires an Eq
instance (you're checking it for equality with 0
) 模拟一些类型类噪声,因为要
add
的第二个参数需要一个Eq
实例(你要检查它与0
相等性)
When we apply fix
to add
, the signature for fix
becomes 当我们应用
fix
add
, fix
的签名变为
fix :: ((a -> a -> a) -> (a -> a -> a)) -> (a -> a -> a)
Remember, the a
s in fix :: (a -> a) -> a
can have any type. 记住,
fix :: (a -> a) -> a
的a
fix :: (a -> a) -> a
可以有任何类型。 In this case they have type (a -> a -> a)
在这种情况下,他们有类型
(a -> a -> a)
Thus fix add :: Num a => a -> a -> a
, which is exactly the right type to add two a
s. 因此
fix add :: Num a => a -> a -> a
,而这正是添加两个正确的类型a
秒。
You can work with Haskell's type signatures in a very algebraic fashion, variable substitution works just like you'd expect. 您可以以非常代数的方式使用Haskell的类型签名,变量替换就像您期望的那样工作。 In fact, theres a direct translation between types and algebra.
事实上,类型和代数之间的直接翻译 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.