What's the standard way to remove element from a list in OCaml?
Asked Answered
S

2

12

In common lisp, we can use the remove function.

It seems there is no such a method in OCaml ?

Stairwell answered 10/11, 2011 at 6:54 Comment(1)
Exactly how should the remove be done? Do you just want to filter the list? (remove, at least in the Common Lisp sense is a very, very scary beast... start/end ranges, counts, keys, and predicates, oh my!)Propeller
S
19

Lists in OCaml are immutable. So you can't remove things from them. You normally create another list that doesn't have the things you don't want. For this, you would use List.filter.

If you absolutely have to have mutable lists, you can. In Batteries there is something called a Dllist that might be like what you want. (It is a doubly linked list, however, unlike a Lisp list).

One of the great things about OCaml, in my opinion, is that the pure functional subset is really quite effective. I've never needed to use mutable lists in my own projects.

Sapsago answered 10/11, 2011 at 7:14 Comment(5)
I see. i should use List.filter.Stairwell
Hi Jeffrey, what if I want to store some elements in one data structure, and and it is not suitable to directly write a recursive function to do that?Rhettrhetta
Short answer: it's always suitable! :-) Longer answer: you can use mutable structures if you have a good reason. You'll have to ask this as a more specific, separate question to get a better answer.Sapsago
Can I make List.filter stop on removing one element? Maybe I have copies of elements that look the same, but only want to remove one.Nisa
To answer my own question, one solution is to use Core's filteri and filter the item with the index of the element you want to remove.Nisa
T
0

below codes returns a new list that remove elements that are equal with specified 'v' from list 'l'.

let remove l v equal =
  let rec aux l' v acc =
    match l' with
    | None -> acc
    | hd :: tl ->
      if equal hd v then
        aux tl v acc
      else
        aux tl v (hd :: acc)
  in
  aux l v []
Threeply answered 25/3, 2023 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.