我可以在Haskell中打印多态函数的类型,就像我将其传递给具体类型的实体时那样吗? [英] Can I print in Haskell the type of a polymorphic function as it would become if I passed to it an entity of a concrete type?

查看:46
本文介绍了我可以在Haskell中打印多态函数的类型,就像我将其传递给具体类型的实体时那样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有3种类型的函数多态性:

Here's a function polymorphic in 3 types:

:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c

,这里是一个非多态函数:

and here a non polymorphic function:

:t Data.Char.digitToInt
Data.Char.digitToInt :: Char -> Int

如果将前者应用于后者,则可以得到一种类型的多态函数:

If we apply the former to the latter, we get a function polymorphic in 1 type:

:t (.) Data.Char.digitToInt
(.) Data.Char.digitToInt :: (a -> Char) -> a -> Int

表示(.)已实例化",(我不确定这是正确的术语;作为C ++程序员,我会这样称呼),其中 b === Char c === Int ,因此应用于 digitToInt (.)的签名如下

which means that (.) was "instantiated" (I'm not sure this is the correct term; as a C++ programmer, I'd call it so) with b === Char and c === Int, so the signature of the (.) that gets applied to digitToInt is the following

(Char -> Int) -> (a -> Char) -> a -> Int

我的问题是:给定(.) digitToInt 和信息",有没有办法在屏幕上打印此签名?我想将前者应用于后者?

My question is: is there a way to have this signature printed on screen, given (.), digitToInt and the "information" that I want to apply the former to the latter?

对于有兴趣的人,此问题已作为此问题的副本被关闭.

For who's interested, this question was earlier closed as duplicate of this one.

推荐答案

其他答案需要使用已经人为限制的类型定义的函数的帮助,例如HTNW答案中的 asTypeOf 函数.这不是必需的,如以下交互所示:

Other answers require the help of functions that have been defined with artificially restricted types, such as the asTypeOf function in the answer from HTNW. This is not necessary, as the following interaction shows:

Prelude> let asAppliedTo f x = const f (f x)

Prelude> :t head `asAppliedTo` "x"
head `asAppliedTo` "x" :: [Char] -> Char

Prelude> :t (.) `asAppliedTo` Data.Char.digitToInt
(.) `asAppliedTo` Data.Char.digitToInt
  :: (Char -> Int) -> (a -> Char) -> a -> Int

这利用了lambda绑定中多态性的 lack ,而lambda绑定中的 asAppliedTo 定义中隐含了该多态性.在其主体中出现的两个 f 必须指定相同的类型,这就是其结果的类型.这里使用的函数 const 也具有其自然类型 a->.b->一个:

This exploits the lack of polymorphism in the lambda-binding that is implicit in the definition of asAppliedTo. Both occurrences of f in its body must be given the same type, and that is the type of its result. The function const used here also has its natural type a -> b -> a:

const x y = x

这篇关于我可以在Haskell中打印多态函数的类型,就像我将其传递给具体类型的实体时那样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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