[英]Haskell Custom Show Instance
我有一个问题,仍在研究家谱树,这是我到目前为止所学到的(抱歉,葡萄牙语单词xD):
data Familia = Node String [Familia]
instance Show Familia where
show (Node a b) = show a ++ "\n\t" ++ show b
raiz :: String -> Familia
raiz n = (Node n [])
juntar :: String -> String -> Familia -> Familia
juntar a b (Node c l)
| b == c = (Node c (l ++ [raiz a]))
| otherwise = (Node c (juntarAux a b l))
juntarAux :: String -> String -> [Familia] -> [Familia]
juntarAux a b [] = []
juntarAux a b [(Node x l)]
| x == b = [(juntar a b (Node x l))]
| otherwise = [(Node x (juntarAux a b l))]
juntarAux a b ((Node x l):xs)
| x == b = (juntar a b (Node x l)):xs
| otherwise = (Node x l):(juntarAux a b xs)
这是我想要的工作方式,事实是,这是我当前的输出:
*Main> let f = raiz "Bob"
*Main> let g = juntar "John" "Bob" f
*Main> g
"Bob"
["John"
[]]
我想要的是这样打印:
Bob
John
Ruth
Hank
因此,家庭的根是鲍勃,鲍勃的儿子是约翰和汉克,约翰有一个叫露丝的女儿。
我已经尝试过用其他方法在其他文章中看到的东西来做这件事,但这是最新的尝试:
instance Show Familia where
show (Node a b) = show a ++ "\n\t" ++ (unlines $ map (unwords . map show) b)
这给了我以下错误:
t4.hs:14:77:
Couldn't match type ‘Familia’ with ‘[a0]’
Expected type: [[a0]]
Actual type: [Familia]
In the second argument of ‘map’, namely ‘b’
In the second argument of ‘($)’, namely
‘map (unwords . map show) b’
有任何想法吗? 提前致谢! :d
表达式map show
是一个需要类型[a]
的参数的函数-因为map
需要一个函数和一个列表。
因此,表达式(unwords . map show)
也是一个期望参数为[a]
类型的函数。
因此,表达式map (unwords . map show)
是一个需要[[a]]
类型参数的函数-它需要一个列表,该列表的每个元素也是一个列表,因为它必须是函数可接受的参数(unwords . map show)
。
因此,在表达map (unwords . map show) b
,最后一个参数b
的类型必须是[[a]]
对于某些a
。
但是从模式Node ab
可以看出, b
是[Familia]
类型-与[[a]]
不兼容。 这就是编译器在错误消息中告诉您的内容。
当您发现自己对嵌套函数的类型感到困惑时,通常最好将它们分开,为每个函数命名(可能是类型)。 这将使您看到错误在哪里。
instance Show Familia where
show (Node a b) = show a ++ "\n\t" ++ concatSubFamilias
where
showSubFamilias :: [String]
showSubFamilias = map show b
concatSubFamilias :: String
concatSubFamilias = unlines showSubFamilias
请注意,上述解决方案不会为您提供所需的结果,因为它不会在嵌套的Familia
之前插入缩进。 我把它留给读者作为练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.