使用函数依赖项,我可以使用多参数类型类约束类型类中的依赖参数类型.像这样:
{-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses,TypeSynonymInstances #-}
class (Num a, Integral b) => F a b | a -> b where
f :: a -> b
instance F Int Int where
f = id
instance F Float Integer where
f = truncate
Run Code Online (Sandbox Code Playgroud)
一切都会很完美.
> f (1 :: Int)
1
> f (1.9 :: Float)
1
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试写类似的东西
instance F Double String where
f = show
Run Code Online (Sandbox Code Playgroud)
我将得到以下编译错误:
No instance for (Integral String)
arising from the superclasses of an instance declaration
Possible fix: add …Run Code Online (Sandbox Code Playgroud)