如何浏览列表并为每个元素返回一些内容?
这是一个小例子:
stack = [("ax","bx"),("cx","dx")]
test :: [(String, String)] -> String
test [] = ""
test (x:xs) = do
reverse (fst x)
test xs
我该怎么做?
答案 0 :(得分:3)
我不太确定你要做什么。如果要反转每个元组的第一个元素并将结果返回到列表中:
stack = [("ax","bx"),("cx","dx")]
test :: [(String, String)] -> [String]
test [] = []
test (x:xs) = reverse (fst x) : test xs
如果您希望将结果作为单个字符串,请尝试:
stack = [("ax","bx"),("cx","dx")]
test :: [(String, String)] -> String
test [] = ""
test (x:xs) = reverse (fst x) ++ test xs
要将函数应用于列表的每个元素,您可能还需要查看map
。
答案 1 :(得分:3)
test = concatMap (reverse . fst)
答案 2 :(得分:0)
test :: [(String, String)] -> String
test = foldr (\x r -> reverse (fst x) ++ r) ""