Haskell 解释器无法推断 return 类型
Haskell interpreter cannot infer return type
我试图实现多态元组映射并最终在 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
所以我的问题是为什么在没有指定的情况下选择单位类型以及如何避免明显的 return 类型定义。
TL;DR 不要使用 GHCi 输入重要代码。将您的代码写入文件并将其加载到 GHCi 中。
您的错误消息提到 Ghci13.Strategy
,它与 Strategy
不同 class。当您有一些代码引用 class 时,GHCi 打印对模块 GhciXXX
的引用,该 class 在 GHCi 会话期间被 重新定义 。您可能有一半代码引用旧的 class,而另一半代码引用新的 class,这会导致混乱。
要重现,请在 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
指的是旧的 class。
我试图实现多态元组映射并最终在 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
所以我的问题是为什么在没有指定的情况下选择单位类型以及如何避免明显的 return 类型定义。
TL;DR 不要使用 GHCi 输入重要代码。将您的代码写入文件并将其加载到 GHCi 中。
您的错误消息提到 Ghci13.Strategy
,它与 Strategy
不同 class。当您有一些代码引用 class 时,GHCi 打印对模块 GhciXXX
的引用,该 class 在 GHCi 会话期间被 重新定义 。您可能有一半代码引用旧的 class,而另一半代码引用新的 class,这会导致混乱。
要重现,请在 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
指的是旧的 class。