gpt4 book ai didi

list - 输出一个元素我想要的次数

转载 作者:行者123 更新时间:2023-12-03 23:33:52 26 4
gpt4 key购买 nike

我有这个代码:

lado ::  [([Char],Int)] -> [[Char]]
lado xs = [a | (a,b) <- xs]

我需要输出这个:

> lado [("A",3),("B",2),("C",1)]
["A","B","C","A","B","A"]

我必须输出 "A"3 次,然后输出 "B"2 次,然后输出 "C"1 次,但我只能用这段代码得到这个 ["A","B","C"]。

最佳答案

您可以使用递归来完成此操作:

lado :: [(a, Int)] -> [a]
-- base case
lado [] = []
-- take each of the non-zero elements then recurse
lado xs = map fst nonzero ++ lado subtracted
where
-- find elements with non-zero count
nonzero = filter (\x -> snd x > 0) xs
-- subtract one from the count for each of those elements
subtracted = map (\(x, n) -> (x, n - 1)) nonzero

关于list - 输出一个元素我想要的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64189254/

26 4 0
文章推荐: R从DF创建JSON列表
文章推荐: c# - 如何在 Xamarin.Forms 中强制使用灯光模式?
文章推荐: google-cloud-platform - 如何将持久存储挂载到 Google Cloud Run?
文章推荐: html - 如何使
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com