我正在努力解决以下问题:
给出:
类型 data T=AA | BB | CC deriving (Show)
输入字符串str
我试图在给定的字符串中查找所有数据构造函数的出现,并将它们附加到输出中:
示例:
输入:"AABCC"
输出: [AA,CC]
基本上,我尝试解析字符串,如果前缀匹配,则将元组的第二个元素附加到结果中,并从输入字符串中截取长度。否则,我将1个元素切成整数,然后重试。
titles = [("AA",AA),("BB",BB),("CC",CC)]
rds::String->[T]
rds str = go str where
go []=[]
go (x:xs)=case filter ((isPrefixOf str).fst) titles of
(name,value):_ ->value:go (drop (length name) (x:xs))
[] -> go xs
该方法仅适用于1个元素,例如"AA"
。当尝试较大的输入时,我得到的是[]
结果。
我认为这与我没有将结果绑定到go
的递归调用有关吗? go
是否必须将结果作为其参数,例如:
go [] str;go result []=result ; go result (x:xs)=....
?
答案 0 :(得分:3)
在
go (x:xs) = case filter ((isPrefixOf str).fst) titles of ...
您可能想要(`isPrefixOf` (x:xs))
。