0

In Haskell you can create where condition for temporary variables like this:

f x
  | cond1 x   = a
  | cond2 x   = g a
  | otherwise = f (h x a)
  where
    a = w x

Is it possible to create this in javascript but with expression not statements.

For example:

let a = 10;
let b = a + 20;

return a + b

This is just simple example which doesn't require temporary variables but it was just example.

The below example is with statements - but I wonder if there is good alternative with expression.

Ramdajs can be used if it appropriate.

Thanks

3 Answers3

1

IIFEs would work:

  (a => (b => a + b)(a + 20))(10)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You can use Javascript's default parameters in a creative way:

const _let = f => f();

const main = _let((a = 10, b = a + 20) =>
  a + b);

console.log(main);

Please note that default parameters aren't evaluated recursively, i.e. the left parameter cannot depend on the right one.

0

The closest thing is a lambda / arrow function, invoked on spot.

Example from Haskell: Where vs. Let (because I do not know Haskell)

f x y  |  y>z           =  ...
       |  y==z          =  ...
       |  y<z           =  ...
     where z = x*x

Could be something like

((x,y)=>{
  let z=x*x;
  if(y>z){console.log("y>z");}
  else if(y==z){console.log("y==z");}
  else /*if(y<z)*/{console.log("y<z");}
})(10,20);

Well, if I understand correctly that f x y | ... is some kind of a switch statement with predicates (which do not really convert to the switch of JS)

tevemadar
  • 12,389
  • 3
  • 21
  • 49
  • Thanks, I will write it with statements, that way is many characters and hard to read –  Dec 17 '19 at 10:55