handy helper I think.
def single!([item]), do: item
def single!(_), do: raise("single item expected")
handy helper I think.
def single!([item]), do: item
def single!(_), do: raise("single item expected")
Is that not equivalent to hd
?
It is quite rare to work with an enumerable which always contains a single element, as in that case, why not just use the element without the enumerable wrapped around it in the first place?
In cases where you are working with lists, you might be able to just use hd
, List.first
or a pattern match ([item] = some_other_variable
, which will raise a MatchError
for any lists other than a list containing a single element.) if you really are in a situation in which you need to extract the first element of a particular list.
(As a side note: your example implementation does not work for any enumerable other than lists.)
It is quite rare to work with an enumerable which always contains a single element
it does not always, but its filtered down to that, eg
cards |> filter_cards(:spades) |> filter_cards(:aces) |> List.single!
I got that quite often.
It is nice to have a way to explicitly say: “now I have to have one item in that list”.
I would write this exactly as @Qqwy suggested:
[card] = cards |> filter_cards(:spades) |> filter_cards(:aces)
This allows expressing more assertions like “no cards”, “one card”, “at least one card”, etc.
OK, I see that this is more idiomatic.
The upside of single
ist that its more explicit.
But most likely I’m just used to Enumerable.Single Method (System.Linq) | Microsoft Docs