avalanche1
avalanche1

Reputation: 3592

How to conditionally assign to a variable in functional way?

I need to assign a value to a variable based on condition. I want to do it with a functional programming paradigm in mind, thus I cannot declare it in outer scope and then reassign.

// let foo = undefined // no-let!
if(condition) {
  const foo = 1
} else {
  const foo = 0
}
do_some_stuff(foo) // Uncaught ReferenceError: foo is not defined

I know, I can use ternary expression here like
const foo = condition ? 1 : 0
but what if I have some other routine to do inside my condition, like:

if(condition) {
  const foo = 1
  do_stuff()
} else {
  const foo = 0
  do_other_stuff()
}
do_third_stuff(foo)

Upvotes: 3

Views: 1623

Answers (3)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

Probably you would encode your case using some algebraic data type (ADT) like Either. That is, you may cover two subcases: left and right.

See the code from // --> Solution starts here onwards. Previous code is a mini standard FP library using vanilla JavaScript to make the code runnable. Check it and enjoy!

// Mini standard library
// -------------------------------

// The identity combinator
// I :: a -> a
const I = x => x

// Either ADT
const Either = (() => {
   // Creates an instance of Either.Right
   //
   // of :: b -> Either a b
   const of = x => ({ right: x })
   
   // Creates an instance of Either.Right
   //
   // Right :: b -> Either a b
   const Right = of
   
   // Creates an instance of Either.Left
   //
   // Left :: a -> Either a b
   const Left = x => ({ left: x })
   
   // Maps Either.Left or Either.Right in a single operation
   //
   // bimap :: (a -> c) -> (b -> d) -> Either a b -> Either c -> d
   const bimap = f => g => ({ left, right }) => left ? Left (f (left)) : Right (g (right))
   
   // Lifts a value to Either based on a condition, where false 
   // results in Left, and true is Right.
   //
   // tagBy :: (a -> Boolean) -> a -> Either a a
   const tagBy = f => x => f (x) ? Right (x) : Left (x)
   
   // Unwraps Either.Left or Either.Right with mapping functions
   //
   // either :: (a -> c) -> (b -> c) -> Either a b -> c
   const either = f => g => ({ left, right }) => left ? f (left) : g (right)
   
   // Unwraps Either.Left or Either.Right and outputs the raw value on them
   //
   // unwrap :: Either a b -> c
   const unwrap = either (I) (I)
   
   return { of, Right, Left, bimap, tagBy, either, unwrap }
}) ()

// --> Solution starts here

// Lifts to Either.Right if x is greater than 3, 
// otherwise, x is encoded as Left.
//
// tagGt3 :: Number -> Either Number Number
const tagGt3 = Either.tagBy (x => x > 3)

// doStuff :: Number -> Number
const doStuff = x => x + 1

// doStuff2 :: Number -> Number
const doStuff2 = x => x * 4

// doStuff3 :: Either Number Number -> Either Number Number
const doStuff3 = Either.bimap (doStuff) (doStuff2) // <-- here's the decision!

const eitherValue1 = doStuff3 (tagGt3 (2))
const eitherValue2 = doStuff3 (tagGt3 (30))


const output1 = Either.unwrap (eitherValue1)
const output2 = Either.unwrap (eitherValue2)

console.log ('output1: ', output1)
console.log ('output2: ', output2)

Refactor using pipes

Now I introduce pipe to glue a composition of one or more unary functions, which makes the code more elegant:

// Mini standard library
// -------------------------------

// The identity combinator
// I :: a -> a
const I = x => x

// Pipes many unary functions
//
// pipe :: [a -> b] -> a -> c
const pipe = xs => x => xs.reduce ((o, f) => f (o), x)

// Either ADT
const Either = (() => {
   // Creates an instance of Either.Right
   //
   // of :: b -> Either a b
   const of = x => ({ right: x })
   
   // Creates an instance of Either.Right
   //
   // Right :: b -> Either a b
   const Right = of
   
   // Creates an instance of Either.Left
   //
   // Left :: a -> Either a b
   const Left = x => ({ left: x })
   
   // Maps Either.Left or Either.Right in a single operation
   //
   // bimap :: (a -> c) -> (b -> d) -> Either a b -> Either c -> d
   const bimap = f => g => ({ left, right }) => left ? Left (f (left)) : Right (g (right))
   
   // Lifts a value to Either based on a condition, where false 
   // results in Left, and true is Right.
   //
   // tagBy :: (a -> Boolean) -> a -> Either a a
   const tagBy = f => x => f (x) ? Right (x) : Left (x)
   
   // Unwraps Either.Left or Either.Right with mapping functions
   //
   // either :: (a -> c) -> (b -> c) -> Either a b -> c
   const either = f => g => ({ left, right }) => left ? f (left) : g (right)
   
   // Unwraps Either.Left or Either.Right and outputs the raw value on them
   //
   // unwrap :: Either a b -> c
   const unwrap = either (I) (I)
   
   return { of, Right, Left, bimap, tagBy, either, unwrap }
}) ()

// --> Solution starts here

// doStuff :: Number -> Number
const doStuff = x => x + 1

// doStuff2 :: Number -> Number
const doStuff2 = x => x * 4

const { tagBy, bimap, unwrap } = Either

// doStuff3 :: Number -> Number
const doStuff3 = pipe ([
   tagBy (x => x > 3),
   bimap (doStuff) (doStuff2), // <-- here's the decision!
   unwrap
])

const output1 = doStuff3 (2)
const output2 = doStuff3 (30)

console.log ('output1: ', output1)
console.log ('output2: ', output2)

Upvotes: 3

Chau Giang
Chau Giang

Reputation: 1554

Because you dont want to declare foo outside, why you do not simply this way:

if(condition) {
  const foo = 1
  do_stuff()
  do_third_stuff(foo)
} else {
  const foo = 0
  do_other_stuff()
  do_third_stuff(foo)
}

Upvotes: 0

Flater
Flater

Reputation: 13803

Nothing is stopping you from splitting the two:

const foo = condition ? 1 : 0;

if(condition) {
    do_stuff();
} else {
    do_other_stuff();
}

do_third_stuff(foo);

In case condition is an expensive execution, simply assign it to a variable before using it multiple times:

let isFoo =  expensiveIsFooMethod();

const foo = isFoo ? 1 : 0;

if(isFoo) {
    do_stuff();
} else {
    do_other_stuff();
}

do_third_stuff(foo);

You're right that it would be cleaner if you didn't have to repeat the condition, but you've introduced this limitation because you're using a const variable which makes it impossible to assign a value to your const in more than one place.

I suggest outweighing the two options here. What matters to you more: cleaner syntax, or ensuring you'll never overwrite the value?

Upvotes: 2

Related Questions