英文:
currying function instead of if condition in javascript
问题
尝试使用柯里化函数来编写条件判断(而不使用 "if"、"true" 和 "false")。不知道如何正确做!有人可以帮助并展示我如何做吗?
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
它应该返回 1 或 2,取决于传递给条件判断的函数是哪个。但是这段代码根本不起作用。
英文:
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.
答案1
得分: 7
使用Church_Booleans可以使用以下函数。
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
英文:
By using Church_Booleans, you could use the following functions.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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
<!-- end snippet -->
答案2
得分: 2
这是一种实现True
、False
和If
的方式,不使用任何控制流语句,如if...else
或switch..case
,也不使用控制流表达式,如?:
,或高阶函数。
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
这是函数解构 Church 编码解决方案的一种去函数化方法。因此,它更高效。
英文:
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.
<!-- begin snippet: js console: true -->
<!-- language: lang-js -->
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
<!-- end snippet -->
This is a defunctionalization of the Church encoding solution. Hence, it's more efficient.
答案3
得分: 1
以下是翻译好的代码部分:
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
英文:
What about this?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论