f# remove from own user defined list

Tags: f#

I want to create a function that removes any occurrence of a integer n and returns the list. I know how I want to do it but do not know the command to delete it.

Here is the data type

type alist = 
  | L of int * Alist

Here's how the data type looks:

let l = L(2, L(1, L(2, L(7, L(3, L(2, A))))))

remove 2 l;;

should return

l = L(1, L(7, L(3, A)))

Here is what I have so far:

let rec remove n l = 
    match (n, l) with
    | (n, A) -> l
    | (n, L(head,tail)) when (n = head) -> 

I don't know how the how to get rid of a list or element.


You shouldn't be thinking in terms of "deleting" the list; you should instead think in terms of building a new list, without the element you want removed. I'll show you how to do that in a minute, but first I want to make a suggestion. In your match expression, you are re-using the name n in your patterns. That's a classic beginner's mistake, because it ends up confusing you. Once you know F# pretty well, that's a valid technique, but since you appear to be a beginner, I strongly suggest not doing that. Instead, use a name in your patterns that is different from the name of the thing you're matching against, because that will help teach you something. Let's rewrite your match expression with x as the name of the int in your patterns:

let rec remove n l = 
    match (n, l) with
    | (x, A) -
By : rmunn

This video can help you solving your question :)
By: admin