Haskell 扩展其返回类型的泛型方法
我将矩阵的数据类型定义为Haskell 扩展其返回类型的泛型方法,haskell,Haskell,我将矩阵的数据类型定义为矩阵a。在我的程序中的大多数地方,我将它与字符串一起用作矩阵字符串,或与其他矩阵一起用作矩阵(矩阵a) 我需要编写一个函数,根据某些规则填充矩阵的内容。对于字符串矩阵,签名应为: pad :: Matrix String -> Matrix (Matrix String) 因为每个字符串都被转换成一定大小的矩阵 对于包含其他矩阵的矩阵,函数应为: pad :: Matrix (Matrix a) -> Matrix (Matrix a) 因为在这种情况下,
矩阵a
。在我的程序中的大多数地方,我将它与字符串一起用作矩阵字符串
,或与其他矩阵一起用作矩阵(矩阵a)
我需要编写一个函数,根据某些规则填充矩阵的内容。对于字符串矩阵,签名应为:
pad :: Matrix String -> Matrix (Matrix String)
因为每个字符串都被转换成一定大小的矩阵
对于包含其他矩阵的矩阵,函数应为:
pad :: Matrix (Matrix a) -> Matrix (Matrix a)
因为在这种情况下,只有内部矩阵的大小在变化
有没有办法概括这两种情况?我试过这个:
class Paddable b => Paddable a where
pad :: a -> Matrix b
然后将字符串
和矩阵a
声明为可填充
,但这失败了,出现了明显的“无法从上下文推断…”错误,这是预期的,因为我没有定义填充
函数来覆盖b
的所有可能值
这里有什么建议吗?在我看来,两个版本的pad在概念上做的事情不同,所以它们可能也有不同的名称。当您在代码中发现一些明显的模式时,定义类型类并不总是一个好主意 也就是说。。。您可以尝试通过以下方式执行操作: 签名是
pad :: Matrix a -> Matrix b
其中b
由a
确定。因此,可以使用以下方法进行:
{-#语言灵活实例,
多线程类型类,
功能依赖性#-}
数据矩阵a=矩阵a导出显示
类可填充a b | a->b其中
焊盘::矩阵a->矩阵b
实例可填充(矩阵a)(矩阵a),其中
pad=id——虚拟实现!
实例可填充字符串(矩阵字符串),其中
pad(矩阵str)=矩阵。矩阵$“>>”++str++>abc
pad :: Matrix a -> Matrix b
{-# LANGUAGE FlexibleInstances,
MultiParamTypeClasses,
FunctionalDependencies #-}
data Matrix a = Matrix a deriving Show
class Paddable a b | a -> b where
pad :: Matrix a -> Matrix b
instance Paddable (Matrix a) (Matrix a) where
pad = id -- dummy implementation!
instance Paddable String (Matrix String) where
pad (Matrix str) = Matrix . Matrix $ ">> " ++ str ++ " <<"
\> pad $ Matrix (Matrix 42)
Matrix (Matrix 42)
\> pad $ Matrix "abc"
Matrix (Matrix ">> abc <<")