Let’s say I have type like this:
= 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
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.
Actually, my code would likely be like this:
case ( cur, component ) of
( Name _, Name _ ) ->
( Speed _, Speed _ ) ->
( _, _ ) ->
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 _ ->
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.
You’re right, in fact I think the resulting code would be clearer this way.
This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.