3 ms·
The List Monad is the same, if a function called with the same input can return one of many results, each time it is called it could return a different output.
by didibus 5y ago
The List Monad is the same, if a function called with the same input can return one of many results, each time it is called it could return a different output. That means this function isn't pure, because a pure function maps the same input to the same output even when called repeatedly.
The difference here is instead of returning a description of the impure things that should be done, you can make the function pure by returning the list of all possible options.
That means instead of getting a different output non-deterministically for the same input each time the function is called, you now get the same output everytime, which is the list of all possible outputs for that input.
So the context is the same, you want to constrain yourself to pure functions for some reason, so how do you make this pure?
func favorite-color(person-name)
if(person-name.startsWith("A")
return randOf("blue", "green")
else
return randOf("yellow", "black")
The trick is to have randOf return a list of all options such as
randOf("blue", "green")
=> ["blue", "green"]
Now you have the same composition problem as before:
func generate-favorite-color-string(favorite-color)
return "My favorite color is: " + favorite-color("Abel")
generate-favorite-color-string(favorite-color("Abel"))
But this won't work again, so you need a Monad once more to help you with composing these pure versions of your impure functions so that:
bind(favorite-color("Abel"),
generate-favorite-color-string)
Which says: compose generate-favorite-color-string with favorite-color using Monads
And now what the Monad composition will do is it will automatically run generate-favorite-color-string for each element in the list returned by favorite-color and itself will return a list of all those possible results:
["My favorite color is: blue",
"My favorite color is: green"]
So the composition is also pure now.