Reputation: 53
I am trying to implement a function that takes an element and a list and removes said element.
This is not producing an output and I'm not sure why. I am new to F# so it is likely that I am making a basic mistake. Note that I am trying to do this using recursion.
Upvotes: 3
Views: 113
Reputation: 24976
Try this.
let rec remove item lst =
let rec removeInner item lst acc =
match lst with
| h::tl when item = h -> removeInner item tl acc
| h::tl -> removeInner item tl (h::acc)
| [] -> List.rev(acc)
removeInner item lst []
[<EntryPoint>]
let main argv =
let result = remove 2 [1;2;2;3;4;2]
printfn "%A" result
0
This is not producing an output and I'm not sure why.
The reason your version is not generating output is because of this line
| [] -> []
it reads: when the list is empty return an empty list.
What you need to do is accumulate the values that are not removed and return the accumulated values as the result.
Using an accumulator with F# is typical for a starter and is created with this line.
removeInner item lst []
The []
at the end is the accumulator, which is an empty list to start with since you have not added anything to it.
Then as you progress you add to it with this line
| h::tl -> removeInner item tl (h::acc)
and lastly you reverse the values in the accumulator and return it with this line
| [] -> List.rev(acc)
Upvotes: 3
Reputation: 9934
I dont know what the intention of your question is, is it really removing or is it writing some recursive function on a list.
The easiest way to achive what you want is:
let remove item lst = List.filter (fun x -> x <> item)
That is: filter out all elements that are equal to your item
Does that help?
Upvotes: 3