我有以下递归数据类型:
data Person boss action = Person{
salary :: Float,
subordinates :: [Person boss action],
act :: action
b :: boss
}我需要一个函数来打印当前人员的所有字段,然后重复调用该函数。据我所见,秀只能有一个论点。我试过这样的方法:
instance (Show boss, Show action) => Show (Person boss action) where
show p = (show (salary p) (act p) (b p)) map (\x -> show x) (subordinates p)发布于 2017-04-29 07:21:11
由于show返回String,您可以通过`++连接show的多个调用:
instance (Show boss, Show action) => Show (Person boss action) where
show p = "salary: " ++ show (salary p) ++ " act " ++ show (act p) ++ " b " ++ show (b p) ++ " subordinates " ++ intercalate "i " (map show (subordinates p))例如,这段代码
import Data.List
data Person boss action = Person {
salary :: Float,
subordinates :: [Person boss action],
act :: action,
b :: boss
}
instance (Show boss, Show action) => Show (Person boss action) where
show p = "salary: " ++ show (salary p) ++ " act " ++ show (act p) ++ " b " ++ show (b p) ++ " subordinates " ++ intercalate "i " (map show (subordinates p))
main =
let
a = Person { salary=1, subordinates=[], act=1, b=1 }
aa = Person { salary=2, subordinates=[a], act=2, b=2 }
in
do
putStrLn $ show aa输出
salary: 2.0 act 2 b 2 subordinates salary: 1.0 act 1 b 1 subordinates顺便提一句,注意
map (\x -> show x) ...可以写成
map show ...https://stackoverflow.com/questions/43692797
复制相似问题