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

Dan*_*kov 0 haskell types type-inference ghc

我试图实现多态元组映射并最终在 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
Run Code Online (Sandbox Code Playgroud)

所以我的问题是为什么在没有指定的情况下选择 Unit 类型以及如何避免明显的返回类型定义。

chi*_*chi 5

TL;DR 不要使用 GHCi 输入非平凡代码。将代码写入文件并将其加载到 GHCi 中。

您的错误消息提到Ghci13.Strategy,这是一个不同的类StrategyGhciXXX当您有一些代码引用在 GHCi 会话期间重新定义的类时,GHCi 会打印对模块的引用。您可能有一半代码引用旧类,另一半引用新类,这会导致混乱。

要重现,请在 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             
Run Code Online (Sandbox Code Playgroud)

注意最后Ghci1.C一个是指旧类。