#`list.map` with a `try` inside

1 messages · Page 1 of 1 (latest)

north finch
#

What is the best way to map a list and then call a function that potentially errors from within?
e.g.

  try mentions =
    map
    |> get_field_safe(
      dyn_atom("mentions"),
      dynamic.list(dynamic.map(dynamic.dynamic, dynamic.dynamic)),
    )
    |> list.map(fn(user_map) {
      try user_cast = user_map
      |> user.from_map
      user_cast
    })
dim crag
#

so you have a List(a), and you have a function fn(a) -> Result(b, error), and you want to try the whole thing and error if any of the items become Error?

dim crag
#

Combines a list of results into a single result. If all elements in the list are Ok then returns an Ok holding the list of values. If any element is Error then returns the first error.

#
try mentions = 
  map
  |> get_field_safe(...)
  |> list.map(...)
  |> result.all
north finch
#

so the list.map should return Result(User, MyError) and then i use result.all to get either Ok(List(User)) or Error(MyError)

dim crag
#

yeah

rough saddle
#

U mean… list.try_map?

dim crag
#

of course that's a thing

rough saddle
#

Lmao

dim crag
#

list module is so bloated i swear 😂

rough saddle
#

Git gud

#

Tbh that one I don’t mind cause I use it all the damn time

#

It’s more performant that a map and all cause it exits early if there’s an error

dim crag
rough saddle
#

Gleam + monads => glonads

#

I’ll take that as a no 😛

north finch
rough saddle
#

Yes lol

north finch
#

xD thanks yeah that worked

eternal pelican
rough saddle
#

@dim crag u know you can always just not import the stdlib 😛

dim crag
native charm
dim crag
#

i feel attacked

eternal pelican
#

why even have a list module

#

we have recursion