计算给定输入类型的函数返回类型

huangapple go评论62阅读模式
英文:

calculate function return type for a given input type

问题

在Haskell中,我想计算给定函数的返回类型,假设已知参数类型。例如,对于具有签名a -> a的函数和参数类型Bool,我想获得返回类型Bool。现在,这个方法可以工作:

-- $ ghci -XScopedTypeVariables
> import Test.QuickCheck
> import Data.Typeable
> fn = id
> param :: Bool <- generate arbitrary
> typeOf $ fn param
Bool

但是,必须实例化参数类型然后执行函数感觉有点繁琐,如果目标只是获取其返回类型的话。

我想象中,如果知道参数类型Bool,我们将知道类型变量a也将变成Bool,因此我们可以将其替换到返回类型a中,以获得返回类型Bool。是否有一种方法可以动态获取这样的函数返回类型,而不必执行函数?

英文:

In Haskell, I would like to calculate the return type for a given function given a parameter type.
So for e.g. a function with signature a -&gt; a and a parameter type Bool, I would like to get the return type Bool.
Now, this works:

-- $ ghci -XScopedTypeVariables
&gt; import Test.QuickCheck
&gt; import Data.Typeable
&gt; fn = id
&gt; param :: Bool &lt;- generate arbitrary
&gt; typeOf $ fn param
Bool

However, having to instantiate the parameter type then execute the function feels a bit overkill, if the goal is just to obtain its return type.

I imagine that, knowing the param type Bool, we would know the type variable a would also become Bool, and that therefore we can substitute this in the return type a as well, to obtain return type Bool.

Is there a way to dynamically obtain such a function return type without having to resort to executing the function?

答案1

得分: 5

请注意,typeOf 不会评估其参数,因此您发布的代码实际上从未调用过 fn

更简洁地说,您甚至可以使用 typeOf $ fn (undefined :: Bool) 将底部参数传递给 fn,而不触发异常。

话虽如此,我无法理解您为什么认为需要在运行时计算类型。在 Haskell 中很少需要这样做。您的实际目标是什么?

英文:

Note that typeOf does not evaluate its argument, so your posted code never actually calls fn.

More succinctly, one can even use typeOf $ fn (undefined :: Bool) to pass a bottom argument to fn without triggering an exception.

That being said, I can not understand why you think you need to compute types a runtime. This is very rarely needed in Haskell. What is your actual goal?

huangapple
  • 本文由 发表于 2020年1月6日 23:17:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定