自定义数据类型的递归

时间:2018-10-15 01:44:52

标签: haskell

我是haskell的新手。
我不确定字符串是否递归。

我举了一个简单的例子。

 data P = P String deriving (Show,Eq,Read)
 data F = F [String] deriving (Show,Eq,Read)

 checkout :: [P] -> F
 checkout [] = F [""]
 checkout (x:xs) = getname x where
     getname (P ame) = F [ame ]
     -- getname (P ame) = F [ame :(getname xs)] I tried like this but it is an error... 

Main>结帐[[P“ S”),(P“ WW”)]-> F [“ S”]

如何获得F [“ S”,“ WW”] ??

另一个问题>

data P = P String Int deriving (Show,Eq,Read)
data F = F [String] [Int] deriving (Show,Eq,Read)

checkout :: [P] -> F
checkout xs = F (removePs xs)
checkout xs = F [ str | (P str _ ) <- xs ]
checkout xs = U [ o | (P _ o ) <- xs ]

我很多余,有什么办法解决吗?

2 个答案:

答案 0 :(得分:1)

首先,您可以构建一个函数P -> String,该函数只需“删除” P构造函数

removeP :: P -> String
removeP (P str) = str

然后,您可以将其应用于列表

removePs :: [P] -> [String]
removePs xs = map removeP xs

最后,我们可以如下利用构造函数F :: [String] -> F

checkout :: [P] -> F
checkout xs = F (removePs xs)

或者,我们可以使用列表理解:

checkout xs = F [ str | (P str) <- xs ]

答案 1 :(得分:0)

一种简单的方法是简单地升级您的getname函数以使用map接受列表:

checkout :: [P] -> [F]
checkout xs = map getname xs where
  getname (P name) = F [name]

但是,如果您确实要显式递归,则可以执行map的实现相同的事情:

checkout :: [P] -> [F]
checkout [] = []
checkout (x:xs) = (getname x : checkout xs) where
  getname (P name) = F [name]