Lua 三目运算符寻找边缘用例

今天我在 codewars 上解决了简单的 The if function kata。 这个 kata 非常简单,它要求实现类似三目运算符 bool ? f1() : f2()function

我非常惊讶,当 return bool and f1() or f2() 的解决方案失败时,有一个隐藏的 case,但 return (bool and f1 or f2)() 的解决方案可以解决问题。

bool and f1() or f2()(bool and f1 or f2)() 不同的情况是什么呢?

点赞
用户8574922
用户8574922

这很简单。我只是找到了一个答案。 不纯函数

  1. true and a() or b() 如果a()返回false,则执行b(),否则执行a()。

  2. (true and a or b)() 只执行a()。

所以在第一种情况下,a()和b()都被执行,并且它们都完成了它们的工作。

local x = 0
function f1() x = x + 1 end
function f2() x = x + 1 end
-- 这个函数触发了f1()和f2()
function if1(b,f1,f2) return b and f1() or f2() end
-- x == 2

x = 0
-- 这个函数只触发f1()
function if2(b,f1,f2) return (b and f1 or f2)() end
-- x == 1
2019-01-27 09:41:28