英文:
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 -> a
and a parameter type Bool
, I would like to get the return type Bool
.
Now, this works:
-- $ ghci -XScopedTypeVariables
> import Test.QuickCheck
> import Data.Typeable
> fn = id
> param :: Bool <- generate arbitrary
> 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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论