Johan
Johan

Reputation: 40558

Get first element from a Set, if it exists, in Haskell

I'm using the containers library and I'm trying to extract the first element out of a set using this approach in the REPL:

let initialSet = insert "x" empty
let setWithTwoElems = insert "y" initialSet
elemAt 0 (filter (\v -> v == "x") setWithTwoElems)

While this works it's not safe if the predicate passed to filter doesn't match any of the elements in the Set. If I do for example:

elemAt 0 (filter (\v -> v == "z") setWithTwoElems)

it'll blow up saying:

"*** Exception: Set.elemAt: index out of range
CallStack (from HasCallStack):
  error, called at libraries/containers/Data/Set/Base.hs:1186:16 in containers-0.5.7.1:Data.Set.Base

which kind of defies the purpose of using Haskell? I'd like something similar to elemAt (or just first) that returns a Maybe result instead.

How can I do this?

Upvotes: 2

Views: 2030

Answers (1)

aochagavia
aochagavia

Reputation: 6256

The function you are looking for is called find and comes from Data.Foldable.

From the documentation:

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

Therefore, you can use find (\v -> v == "x") setWithTwoElems

Upvotes: 6

Related Questions