Reputation: 115
Tried to use curry function to write if condition (without "if" "true" and "false"). Have no idea how to do it right! Can anyone help and show me how to do it?
const True = () => {};
const False = () => {};
const If = True => False => ifFunction(True)(False);
const ifFunction = If(True);
ifFunction('1')('2'); // 1
console.log(If(True)('1')('2')); // 1
console.log(If(False)('1')('2')); // 2
It should return 1 or 2 depends on which function is getting pass to if condition. But this code does not work at all.
Upvotes: 6
Views: 915
Reputation: 74204
Here's a way to implement True
, False
, and If
without using any control flow statements like if...else
or switch..case
, control flow expressions like ?:
, or higher-order functions.
const True = 1;
const False = 0;
const If = Bool => Then => Else => [Else, Then][Bool];
console.log(If(True)('1')('2')); // 1
console.log(If(False)('1')('2')); // 2
This is a defunctionalization of the Church encoding solution. Hence, it's more efficient.
Upvotes: 2
Reputation: 386578
By using Church_Booleans, you could use the following functions.
const
TRUE = a => b => a,
FALSE = a => b => b,
IF = p => a => b => p(a)(b);
console.log(IF(TRUE)('1')('2')); // 1
console.log(IF(FALSE)('1')('2')); // 2
Upvotes: 7
Reputation: 16847
What about this?
const True = () => true;
const False = () => false;
const If = exp => exp() ? a => b => a : a => b => b;
console.log(If(True)('1')('2')); // 1
console.log(If(False)('1')('2')); // 2
Upvotes: 1