简体   繁体   English

记录类型Haskell中的多态函数

[英]Polymorphic functions in Record Types Haskell

i've stumbled upon a behaviour I can't explain in Haskell. 我偶然发现了一个我无法在Haskell中解释的行为。 I'm trying to store a polymorphic function in a Record Type, which I want to use in a ReaderT Monad. 我正在尝试将多态函数存储在Record Type中,我想在ReaderT Monad中使用它。 When I get my function with asks , the compiler doesn't recognize it as polymorphic and seems to fix the type on the first occurance of the function. 当我得到我的功能与asks ,编译器不会将其识别为多态,似乎固定在函数中第一次出现的类型。 I created a minimal example of this in ghci: 我在ghci中创建了一个最小的例子:

{-# LANGUAGE Rank2Types             #-}

data Test = Test {f :: (forall a. a -> a)}

runReaderT (asks f 
            >>= \f -> (liftIO . putStrLn $ show (f 2 :: Int)) 
                   >> (liftIO . putStrLn $ show (f "hello"))
           ) (Test id)

When trying to run this, I get: 在尝试运行时,我得到:

Couldn't match expected type ‘Int’ with actual type ‘[Char]’
In the first argument of ‘f’, namely ‘"hello"’
In the first argument of ‘show’, namely ‘(f "hello")’
In the second argument of ‘($)’, namely ‘show (f "hello")’

However, following code works: 但是,以下代码有效:

runReaderT (ask 
            >>= \(Test f) -> (liftIO . putStrLn $ show (f 2 :: Int))     
                          >> (liftIO . putStrLn $ show (f "hello"))
           ) (Test id)

So is it something special with asks ? 因此,它是特别的东西用asks I'm grateful for any advice on this. 我对此提出任何建议表示感谢。

Last time I checked, GHC could not infer higher rank types. 上次我检查时,GHC无法推断出更高等级的类型。 Thus, when you have 因此,当你有

\f ->  ... f x .... f y

the f can never be polymorphic. f永远不会是多态的。

There are only two places where the type of some variable is so obvious that type inference recognizes the higher rank type: in patterns that declare higher rank fields and in the LHS of annotated functions. 只有两个地方,某些变量的类型是如此明显,以至于类型推断识别出更高级别的类型:在声明更高等级字段的模式中和在带注释函数的LHS中。

It also should work to give the type explicitly, like in 它也应该明确地给出类型,比如

\(f :: forall a.a -> a) -> .... f x ... f y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM