Find by type value

Hello there!
Let’s say I have type like this:

type Component 
    = Name String 
    | Speed Float

Would it be possible to write a function allowing to find, in a List Component, a specific variant, like Name “Yoda”? I imagined a function type like this one, but I have no Idea if the implementation is possible…

getComponent a -> List Component -> Maybe a

Thanks

Maybe something like this: https://gist.github.com/ni-ko-o-kin/95ae359bd0ac13a5ef9036fea1dfce2c

I’m not 100% sure if I understood the intend behind this, but you could use https://package.elm-lang.org/packages/elm-community/list-extra/latest/List-Extra#find to get the item

@ni-ko-o-kin thank you. I think this would work, even if as I was afraid of, we need to explicitly check every case.

@razze this function is useful, but in my case the problem is how to write the predicate ^^

I added a second find (find2)… little bit simpler but not as efficient.

EDIT: If you want to use List-Extras (@razze mentioned it) you can use the go function in the find2 example as a predicate.

Thank you!

Actually, my code would likely be like this:

case ( cur, component ) of
    ( Name _, Name _ ) ->
        True

    ( Speed _, Speed _ ) ->
        True

    ( _, _ ) ->
       False

All I want is to find a Name or a Speed in the list of components.

You could also write the predicate functions like this:

findName : Component -> Boolean
findName component =
    case component of
        Name _ ->
            True
        _ ->
            False

And then repeat for every value constructor. I never saw this problem solved any other way. I guess that’s how you solve such things in a statically typed language. Correct me if I’m wrong.

1 Like

You’re right, in fact I think the resulting code would be clearer this way.