Instructor: 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.