Haskell解释器无法推断返回类型

问题描述 投票:0回答:1

[我试图实现多态元组映射,并最终在GHCi中进行了如下编写:

data MaxS = MaxS
class Strategy action input result | input -> result where  
    work :: action -> input -> result
instance (Ord a) => Strategy MaxS (a, a, a) a where work _ (a, b, c) = max a (max b c)
f :: (Strategy action input result) => action -> input -> result ; f a i = work a i
f MaxS (1, 2, 3)   

<interactive>:91:1: error:
    * No instance for (Ghci13.Strategy
                         MaxS (Integer, Integer, Integer) ())
        arising from a use of `it'
    * In the first argument of `print', namely `it'
      In a stmt of an interactive GHCi command: print it

f MaxS (1, 2, 3) :: Integer
3

所以我的问题是,如果未指定任何内容,为什么选择单元类型,以及如何避免明显的返回类型定义。

haskell types ghc type-inference
1个回答
0
投票

TL; DR请勿使用GHCi输入不重要的代码。将您的代码写入文件,然后将其加载到GHCi中。

您的代码提到Ghci13.Strategy,这是与Strategy不同的类。当您有一些代码引用在GHCi会话期间redefined的类时,GHCi将打印对模块GhciXXX的引用。您可能有一半的代码引用了旧的类,另一半的代码引用了新的类,这会导致混乱。

要复制,请在GHCi中尝试:

> class C a where foo :: a -> Bool 
> bar = foo                        
> class C a where foo :: a -> Int  
> :t foo                           
foo :: C a => a -> Int                    
> :t bar                           
bar :: Ghci1.C a => a -> Bool             

注意最后一个指向旧类的Ghci1.C

© www.soinside.com 2019 - 2024. All rights reserved.