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
                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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With