Find and Delete the Functional Way
Let's say, in Elm, you have a model contains a list of objects, like this:
type alias Task = {
name: String,
status: String
}
type alias Model = {
tasks: List Task
}
And you're making a CRUD application.
You can easily add a new Task
into the model in the functional way, very simple:
newModel = { model | tasks = model.tasks ++ [ Task "Imma new task" "To Do" ] }
Now you want to write a deleteTask
function, let's keep it simple, this function expects a String
, and remove the Task
has that string as a name
.
In imperative way, we can iterate through the List
, looking for an item that matched the search condition, obtain its index and remove any item at that index.
In functional way, iterating is such a PITA. So you don't wanna do it. Instead of thinking how to find the index of an item, then remove it (which consist two actions, or expressions), let's think differently. What if we can look for an item, and remove it at the same time?
Just like using map
(apply some function to every item in the list, returns a new list), we have filter
(apply a filter to every item in the list, return a new list that contains any item that matched). So in this case, we just need to filter out the desired item from the list.
newModel = { model | tasks = List.filter (\x -> x.name /= name) model.tasks }
That's it.
Hey, what? Is this seems obvious?
Yeh, it's it. For people who came from a functional programming background. But it's not the "natural way of thinking" for people who came from imperative languages.
And this is what I really like when learning FP. You gotta think differently to solve the problem.