Stream: beginners

Topic: List index


view this post on Zulip Qqwy / Marten (Jun 17 2022 at 15:08):

Is there a simple way to find the index of a particular element in a list?

view this post on Zulip Qqwy / Marten (Jun 17 2022 at 15:09):

Essentially, instead of find : (List elem), (elem -> Bool) -> (Result elem [ NotFound ]*) I'm looking for findIndex : (List elem), (elem -> Bool) -> (Result Nat [ NotFound ]*)

view this post on Zulip Qqwy / Marten (Jun 17 2022 at 15:10):

So that it can be used for later operations with get, set, replace, split etc.

view this post on Zulip Brendan Hansknecht (Jun 17 2022 at 16:33):

There should be a List.find, but maybe it hasn't been implemented yet

view this post on Zulip Brendan Hansknecht (Jun 17 2022 at 16:34):

If it doesn't exist, it could be built with List.walkUntil

view this post on Zulip Brendan Hansknecht (Jun 17 2022 at 16:36):

Just make the state the current index. Increment it in the looping function. Check the element against a predicate each round. Return the index when an element matches and stop the walk.

view this post on Zulip Brendan Hansknecht (Jun 17 2022 at 16:37):

Also, probably can get List.findIndex or something similar added to the standard library, I think it is a common enough use case to merit its own function.


Last updated: Jul 05 2025 at 12:14 UTC