On Fri, Oct 7, 2016 at 11:02 PM, Dave Ford <[email protected]> wrote:

> On Fri, Oct 7, 2016 at 11:10 AM, Peter Damoc <[email protected]> wrote:
>>
>> If you can come up with a practical scenario where you would have an
>> exception, I or someone else around here could tell you what would happen
>> in Elm in that context.
>>
> Yes. The example I gave when I started the thread (sorry for the java
> syntax - i'm new):
>
> function foo(int x) throws IllegalArgumentException{
>   if(x > 10) throw new IllegalArgumentException("Bad x");
>   return x * x * x;
> }
>


Doesn't the caller of the function needs to try/catch the exception in
Java, in other words, needs to deal with this exception?

In any case, in Elm this function needs to evaluate to something and, since
it only works on x smaller than 10, this means that it needs to produce a
Maybe Int.
If you give it something smaller than 10 it produces the Just x*x*x
If you give it something larger than 10 it should produce Nothing.

Now, if you need to add 10 to the result of this, you have to choices:
Either default the result to some value (if that's sensible), OR, you can
say... not my business.

let's imagine a large chain where you have

add10 = a function that adds 10 to any integer

multiply3 = a function that multiplies any integer

subtract5 = a function that subtracts 5

and you want to apply all three to this function that raises to the 3rd
power only if x is smaller than 10.

the way you do it is like this

finalValue =
    toTheThirdIfSmallerThan10 someValue
    |> Maybe.map (add10 >> multiply3 >> subtract5)

this will result in a Maybe that has all those functions applied to the
result of the toTheThirdIfSmallerThan10 if someValue is smaller than 10 OR
Nothing otherwise.

add10, multiply3 and subtract5 are regular Int->Int functions.
You don't need to handle the Maybe in each of them.


-- 
There is NO FATE, we are the creators.
blog: http://damoc.ro/

-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to