I am new to functional programming and have some problems with the task of list processing. I have a set of records, such as:
type TestRec = { Id : string Amount : int }
Now I want to delete all the items in the list that pair with each other. For example, if there are two items with Amount
of 7
and -7
, both items should be removed from the list. If there is a third element with Amount = 7
, it should remain in the list.
I hope you guys understand what I'm trying to do. This is what I came up with so far (but it does not work correctly):
let removeDoubles items = items |> Seq.groupBy (fun i -> Math.Abs(i.Amount)) |> Seq.map snd |> Seq.filter (fun i -> Seq.length i = 1)
Edit: A function that determines the coincidence of two elements with each other can be more complex than described above ( Math.Abs
). I thought this would be a good example with Amount
values, but it could be any predicate function.
Edit 2: To clarify something else, I want to give a more realistic description of a possible related problem. You can submit an invoice calculation in which the list consists of all invoice items. Now you want to delete all pairs of account positions that have, for example, the same “article number”, “currency” and prices are valued to zero.
Perhaps this example helps explain my problem. I just thought that there might be a more “functional way” to solve this problem than having two loops over the list and removing elements like I would do in an imperative language.
source share