Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save punmechanic/f021348dbf7dec8c7a385eb08f30f535 to your computer and use it in GitHub Desktop.
Save punmechanic/f021348dbf7dec8c7a385eb08f30f535 to your computer and use it in GitHub Desktop.
{-
Upserts into the given list, based on the given predicate.
If the given predicate matches any element in the list, then the first element
that matches that predicate in the list has the given function applied to it. A
new list is then returned with the new element present.
If the given predicate does not match any elements in the list, then the given
default element is inserted.
Yes, this is a very contrived hack used to work around the fact that I'm using
a list and not a map. Sue me.
-}
upsertIntoList : (a -> Bool) -> (a -> a) -> a -> List a -> List a
upsertIntoList predicate update default list =
case list of
-- This syntax works on lists with one element, that is,
-- [1] will mean x is 1 and xs is []
(x::xs) ->
-- Elm plz give us where expressions :/
if predicate x then
update x::xs
else
upsertIntoList predicate update default xs
-- We will only ever reach this case if there are no elements in the list
-- and we have not updated any previous elements
[] ->
[default]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment