Sen*_*eno 2 polymorphism haskell function-composition
我有以下文件:
module SimpleComposition where
class Intermediate a where
f :: a -> Int
g :: Char -> a
h :: Char -> Int
h = f . g
Run Code Online (Sandbox Code Playgroud)
尝试在 ghci 中加载它时,出现错误:
main.hs:8:5: error:
* No instance for (Intermediate a0) arising from a use of `f'
* In the first argument of `(.)', namely `f'
In the expression: f . g
In an equation for `h': h = f . g
|
8 | h = f . g
| ^
Run Code Online (Sandbox Code Playgroud)
我相信问题在于有人可能使用了 2 种不同的类型,它们是Intermediate此组合中的实例。当我导出这个模块时如何保证它是相同的?
PS:这是我遇到的问题的一个更好的最小示例,而不是我之前提出的问题(如何在 Haskell 中组合多态函数?)。
问题并不是不能推断出实例,而是编译器确实无法知道您可能想要的类型。g可以产生从它请求的任何类型(假设它有一个Intermediate实例),f可以使用任何这样的类型......但没有人指定哪个.
但这很容易解决:现在只需选择一种类型。当然,它必须是有实例的;例如,如果你有
instance Intermediate Char where
f = fromEnum
g = id
Run Code Online (Sandbox Code Playgroud)
然后你可以使用
h :: Char -> Int
h = (f :: Char -> Int) . g
Run Code Online (Sandbox Code Playgroud)
修复类型选择的更简洁方法是使用语法扩展:
{-# LANGUAGE TypeApplications #-}
h = f @Char . g
Run Code Online (Sandbox Code Playgroud)
...或者,为了强调您只是在中间固定类型,
h = f . id @Char . g
Run Code Online (Sandbox Code Playgroud)