通过函数依赖,我可以使用多参数类型类来约束类型类中依赖参数的类型。就像这样:
{-# 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
一切都会完美地进行。
> f (1 :: Int)
1
> f (1.9 :: Float)
1
但是如果我尝试写一些类似的东西
instance F Double String where
f = show
我会收到以下编译错误:
No instance for (Integral String)
arising from the superclasses of an instance declaration
Possible fix: add an instance declaration for (Integral String)
In the instance declaration for `F Double String'
有没有办法用类型族而不是fundeps来解决这个问题?
最佳答案
基本上不是,这实际上与函数依赖(或类型族)无关。你的类定义有
class (Num a, Integral b) => F a b
它声明 b
必须有一个 Integral 实例。 String
没有 Integral 实例,因此除非您定义,否则您不能拥有 F a String
形式的任何内容
-- String is a type synonym for [Char]
instance Integral [Char] where
我不知道这通常是否明智。如果在系统中为字符串创建 Integral 实例有意义,您可能希望在字符串周围放置一个新类型包装器并为其创建实例。
关于haskell - 函数依赖/类型族,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5624438/