How to delete an item in a list?

I would like to delete an item from a list{} using Belt.List

I see that the API has method to add, get and check has but I don’t see any method to remove. So far I would remove the item by using keep or reduce but I wonder if I’m missing something. I find it strange that there is no remove method without having to set an association.

I don’t think you’re missing anything, since keep is exactly for this purpose. i.e.: let remove_zeroes = l => Belt.List.keep(l, x => x != 0) . Between keep and reduce, keep should be more efficient AFAIK.

I guess a function named remove may be more discoverable, but it would just work exactly like keep does except backwards (keeping items where the callback returns false instead of true).

1 Like

What are you using a list for? I’m curious because the general advice is to use arrays unless you have a good reason to use lists.

I am exploring on using them as a list of input errors

type error = ErrorAccount | ErrorName | ErrorPhone

// react component
let (errors, set_errors) = React.useState(_=> list{})

//... on form submit: set errors
// show error if in the list
{ errors->List.has(ErrorPhone) ? "Invalid phone number" : React.null }

that way I don’t have to make a state for each error.

OK, I see why you want an immutable data structure like a list. But I would actually recommend to use a Belt.Set here instead of a list, as it is more suitable. It’s an immutable data structure as well, and it has ‘add’, ‘remove’, and ‘has’ operations directly instead of indirectly with ‘keep’. You’ll just need a couple of extra lines to set up the comparator for your custom type, after that it’s pretty simple to use.

3 Likes

Thanks, sounds like a better option. That way I don’t need extra conditionals with the has + keep I can just use remove

For only three kinds of errors, you may even be better off using a record:

type error = {account: bool, name: bool, phone: bool}

// later:
{ errors.phone ? "Invalid phone number" : React.null }

IMO, lists are only worthwhile if you’re taking advantage of pattern matching. If you’re mostly using the List functions, then a different type is probably better.

2 Likes

so true… sounds like I was overengineering it. At least now I learned more about how to use Sets :slight_smile:

The reason this method won’t exist is because OCaml completely separates data from functions/methods.

In OOP, you can add methods to classes, and call those methods. If one of those methods is isEqual, you’d implement the remove function by calling that method.

But in OCaml, data doesn’t have methods. If you wanted to make this method, you’d have to pass in an isEqual method (along with the element you want to remove). It’s easier to just have filter.

OCaml does have a generic isEqual method (eq) - but you really wanna avoid it for complicated data types.

2 Likes