Haskell 递归显示数据类型
我有以下递归数据类型:Haskell 递归显示数据类型,haskell,Haskell,我有以下递归数据类型: data Person boss action = Person{ salary :: Float, subordinates :: [Person boss action], act :: action b :: boss } 我需要一个函数来打印当前人员的所有字段,然后重复调用该函数。从我所看到的来看,这个节目只能有一个论点。我试着说: instance (Show boss, Show action) => Show (Person bo
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)
由于
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 ...
你是对的。。lambda函数是不必要的。