【问题标题】:Haskell interpreter cannot infer return typeHaskell 解释器无法推断返回类型
【发布时间】:2019-12-23 22:06:42
【问题描述】:

我试图实现多态元组映射,并最终在 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

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

【问题讨论】:

    标签: haskell types ghc type-inference


    【解决方案1】:

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

    您的错误消息提到Ghci13.Strategy,它与Strategy 不同。当您有一些代码引用在 GHCi 会话期间 重新定义 的类时,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,它指的是旧类。

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多