Reputation: 814
I have a piece of code like this
if (result-of-a-func-call) > 0
then (result-of-a-func-call)
else -2
Is there a way to avoid calling the same function (with the same parameters) the second time? In an imperative language, we can do something like
if((result=func-call())>0)
result
else
-2
Upvotes: 2
Views: 1075
Reputation: 12070
I would use case
case theFunction x of
x | x < 0 -> -2
x -> x
That being said, this looks like a c style error detection to me (ie- if result of function is < 0, there is an error, otherwise the result is the value). In Haskell, don't do this!
Instead use monads. For instance, use Maybe.
case theFunction x of
Nothing -> handle error
Just x -> x
(if handling the error just means passing it up to the next level, you often won't even need the case
at all, the monad logic will handle it correctly)
You can do something similar using Either
, where you can distinguish between error types.
Upvotes: 3
Reputation: 54068
You can do this using let
or where
:
f x =
let y = g x
in if y > 0 then y else -2
Or
f x = if y > 0 then y else -2
where y = g x
There are subtle differences between the two here, the biggest one to keep in mind is that where
can be used to define values that don't change in between function calls and the compiler will only define the value once, while a local let
will be defined every time the function is called, e.g.
f x = g x
where g y = y * y + 1
versus
f x =
let g y = y * y + 1
in g x
In the first example, g
is defined only once since it does not depend on any of f
's arguments (x
), while in the second example g
is redefined every time f
is called. There are reasons for wanting both approaches that are beyond the scope of this answer.
Upvotes: 6