Haskell代数类型和函数转换

时间:2012-12-27 16:23:17

标签: list haskell algebraic-data-types

我要制作一个将House变为NH的功能。

data House = House { hworking :: Working, hfinished :: Finished}

type Working = [Roof] , type Finished = [Roof]

data NHouse = NHouse {rot :: [NRoof]} 

data NRoof = NRoof {h :: Roof, st :: Status }

data Status = Working | Finished

我曾经想过要做一个辅助功能,用一个NRoof转换每个屋顶,然后将它转移到屋内的每个屋顶。

但我无法弄明白。我正在做这样的事情:

nWorking :: Roof -> NRoof
nWorking x = NRoof {x, Working }

1 个答案:

答案 0 :(得分:1)

是的,你正朝着正确的方向前进。您可以创建一个函数,在给定状态的情况下将Roof转换为NRoof

transform :: Status -> Roof -> NRoof
transform s r = NRoof r s

然后你可以将这个功能映射到你家里的屋顶列表上。

h2n :: House -> NHouse
h2n (House w f) = NHouse $
                map (transform Working) w ++
                map (transform Finished) f

在一行中,这可以写成

h2n (House w f) = NHouse $ map (flip NRoof Working) w ++ map (flip NRoof Finished) f