6

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.

3
  • 2
    Look for the Lambda Calculus. Commented Jan 6, 2020 at 10:46
  • 4
    Also, take a look at church booleans Commented Jan 6, 2020 at 10:53
  • 1
    For the record, here is Ramda's implementation of ifElse which implements ifElse(conditionFn, trueBranchFn, falseBranchFn). The library uses a simple conditional operator as the implementation (simplified): conditionFn() ? trueBranchFn() : falseBranchFn() Commented Jan 6, 2020 at 11:05

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

You can accept truthy/falsy values if you modify [Bool] to [Number(!!Bool)].
1

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

1 Comment

thank you. but I trying to do it without "if" (even ternary)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.