不同情况下使用的多态变量haskell [英] Polymorphic variable used in different contexts haskell
本文介绍了不同情况下使用的多态变量haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一段Haskell代码:
I have a following piece of Haskell code:
foo :: Num a => (a -> a) -> Either Integer Double -> Either Integer Double
foo f x = case x of
Left i -> Left $ f i
Right d -> Right $ f d
它不会编译时出现错误无法匹配整型与双精度。我知道 f
类型的计算方式为整数 - >整数
和双精度 - > Double 在
左
和右
表达式中分别创建冲突。
It doesn't compile with error "Couldn't match type Integer with Double". I understand that type of f
is computed as Integer -> Integer
and Double -> Double
in Left
and Right
expressions respectively, creating a collision.
如何更改此函数,以便每次使用正确版本的 f
?
How can I change this function, so that correct version of f
would be used each time?
推荐答案
您需要 RankNTypes
。
{-# LANGUAGE RankNTypes #-}
foo :: (forall a. Num a => a -> a) -> Either Integer Double -> Either Integer Double
foo f x = case x of
Left i -> Left $ f i
Right d -> Right $ f d
这篇关于不同情况下使用的多态变量haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文