如何在ghci中查询统一类型?

4

是否可以查询ghci的统一类型?

例如,如果我想知道 (Int -> Bool)(a -> Bool) 之间的统一类型,我如何查询ghci呢?

我尝试解决的问题是第三版函数式编程的Haskell实践中的练习13.23。

How can you use the Haskell system to check whether two type expressions are unifiable, and if so what is their unification? Hint: you can make dummy definitions in Haskell in which the defined value, zircon say, is equated with itself:

zircon = zircon

Values defined like this can be declared to have any type you wish.

谢谢,
Sebastián。

1个回答

5

一种方法是使用asTypeOf:: a -> a -> a。作为一个函数,asTypeOf并不是很有趣,但它的类型很好:它强制其两个参数和返回类型统一。所以:

> :t asTypeOf (undefined :: Int -> Bool) (undefined :: a -> Bool)
asTypeOf (undefined :: Int -> Bool) (undefined :: a -> Bool)
  :: Int -> Bool

您可以看到这两种类型合并为 Int -> Bool。对于一个稍微有趣一点的例子,让我们统一 Maybe af (Bool, c):

> :t asTypeOf (undefined :: Maybe a) (undefined :: f (Bool, c))
asTypeOf (undefined :: Maybe a) (undefined :: f (Bool, c))
  :: Maybe (Bool, c)

另一方面,为了练习,我鼓励你手动尝试统一操作。一旦你掌握了技巧,它并不难,并且是一项你将反复使用的技能。


1
还可以使用列表构造器 :t [undefined :: Maybe a, undefined :: f (Bool, c)] - max taldykin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接