Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid calling the same function with the same parameters twice?

Tags:

haskell

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
like image 573
Fractal Avatar asked Nov 30 '25 06:11

Fractal


1 Answers

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.

like image 111
bheklilr Avatar answered Dec 01 '25 19:12

bheklilr