编写更新函数haskell

时间:2017-04-03 16:02:15

标签: haskell

我想创建以下类型的2个输入的更新功能。它所做的就是它在给定整数的列表中找到n个相同的整数,删除它们并返回一个包含所有先前元素的新列表以及尾部中的n个删除整数。

Int->[Int]->[Int]

示例:

>update 1 []
[1]
>update 2 [2]
[2]
>update 3 [3,4,3,5,3,6]
[4,5,6,3]

2 个答案:

答案 0 :(得分:1)

根据我对你的问题的理解,这就是我写的更新功能。

update :: Int -> [Int] -> [Int]
update n ns = [ x | x <- ns, x /= n] ++ [n]

答案 1 :(得分:1)

以防万一&#34; n&#34;是指出现次数,您的示例未指定:

import Data.List (foldl')

count y  =  foldl' (n x -> if x == y then n + 1 else n) 0
update y xs = filter (/= y) xs ++ replicate (count y xs) y

或者,使用单遍历partition

update y xs = let (ys, other) = partition (== y) xs in other ++ ys