显示递归数据类型

时间:2017-04-29 07:05:01

标签: haskell

我有以下递归数据类型:

data Person boss action = Person{
  salary  :: Float,
  subordinates :: [Person boss action],
  act :: action
  b :: boss
 }

我需要一个函数来打印当前Person的所有字段,然后重复调用该函数。从我所看到的展示只能采取一个论点。我正在尝试这样的事情:

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)

1 个答案:

答案 0 :(得分:1)

由于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 ...

可以写成

{{1}}