Make your own functions safer by lifting them into a Maybe context

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 years ago

You probably have functions that aren’t equipped to accept a Maybe as an argument. And in most cases, altering functions to accept a specific container type isn’t desirable. You could use map, passing in your function, or you could “lift” your function into a Maybe context. In this lesson, we’ll look at how we can get a function that accepts raw values to work with our Maybe container without the need to modify the original function or the input values.

Instructor: [00:00] We're pulling in a utility function called double that takes in a number and returns the result by doubling. We've defined an input constant with a value of 2, and we're getting the result of applying double to the input, which gives us 4.

[00:12] If our value isn't a number, we'll get not-a-number as a result, which probably isn't going to play well with the code that uses this result. Let's use the is-number and safe functions that we're pulling in from the Crux library to make a new function, which we'll call safe-double.

[00:32] Safe-double is going to take in our number just like our double utility, but then we're going to call safe, pass in is-number as our predicate, and then passing it in. This is going to give us a maybe of our number.

[00:43] We'll get just wrapping our 2 for the case of input, and if we pass in something that is not a number, we'll get a nothing. Now we can call map, and we can pass in double to apply double to the value that's wrapped in our just.

[00:57] Then I'll drop down here, and I'm going to replace this call to double with a call to safe-double. You'll see that now we're going to get just 4.

[01:04] Any code that's using this result is going to expect a number, so we can unwrap this value by calling the option method and passing it a default in the case of a nothing to make zero. Now we're going to get out number back out of there.

[01:17] If we change the input and we make it a string again, we'll get a default value of 0Adding safety around an existing function is pretty common. Crux gives us a handy utility that we can use to shorten up our code a little bit.

[01:30] I'm going to come up here, and I'm going to also import a utility function called safe-lift from Crux. I'm going to come down here, and I'm going to call in out this existing safe double. We're going to redefine that.

[01:43] This time, I'm going to call safe-lift, and I'm going to pass it the predicate that we used to check our type. I'm going to pass it the function that I want to put the safety around, which in this case is double. We'll see down here that everything is back to working.

[01:58] Safe-lift has taken our existing double function, and lifted it into the maybe context, and it's using is-number to check the argument that's passed into it.