Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a single record from a list of records in Elm

Tags:

elm

I’m trying to return a single record from a list of records when a condition is met. Right now I’m returning a record with empty fields when the condition is false.

Is this OK? Is there a better way?

xs =
    [ { name = "Mike", id = 1 }
    , { name = "Paul", id = 2 }
    , { name = "Susan", id = 3 }
    ]


getNth id xs =
    let
        x =
            List.filter (\i -> i.id == id) xs
    in
        case List.head x of
            Nothing ->
                { name = "", id = 0 }

            Just item ->
                item
like image 589
Jose Ortega Avatar asked Oct 25 '25 14:10

Jose Ortega


1 Answers

There is no search function for lists in the core List package, but the community has one in the List-Extra. With this function, the above program can be written:

import List.Extra exposing (find)

getNth n xs =
  xs 
  |> find (.id >> (==) n)
  |> Maybe.withDefault { id = n, name = "" }

The canonical way to handle the "there might not be a value" in Elm is to return a Maybe value—this way, the user of getNth can choose what should be done when the value he is looking for cannot be found. So I'd prefer to leave out the last line, arriving at the very neat:

getNth n = find (.id >> (==) n)
like image 76
Søren Debois Avatar answered Oct 28 '25 04:10

Søren Debois