为什么在IF语句中使用map会出现问题?

huangapple go评论92阅读模式
英文:

Why are there problems using map in an IF statement?

问题

为什么以下代码无法运行?

if (map [ [a b c] -> a + b = c ] [1] [2] [3]) [show 100]

以下代码的输出结果为'true':

show (map [ [a b c] -> a + b = c ] [1] [2] [3])

所以我期望上面的第一个语句与下面的语句相同:

if true [show 100]

(附注:在我的完整版本中,列表更长,但使用reduce折叠成单个true/false。)

谢谢。

英文:

Why won't the following run?

if (map [ [a b c] -> a + b = c ] [1] [2] [3]) [show 100]

The following produces 'true' as an output:

show (map [ [a b c] -> a + b = c ] [1] [2] [3])

so I expected the first statement above to be the same as:

if true [show 100]

(P.S. in my full version the lists are longer but are collapsed into a single true/false using reduce.)

Thanks.

答案1

得分: 1

为了详细说明ThomasC的评论,map函数总是生成一个列表,即使它只有一个元素。

因此,以下代码:

(map [ [a b c] -> a + b = c ] [1 2] [2 3] [3 5])

会生成[true true]。在这里,reduce函数很有帮助:

(reduce AND (map [ [a b c] -> a + b = c ] [1 2] [2 3] [3 5]))

通过"与"所有map输出的元素,会生成一个简单的true

而以下代码:

(reduce AND (map [ [a b c] -> a + b = c ] [1 2] [2 3] [3 6]))

会生成一个简单的false

英文:

To elaborate on ThomasC's comment, map always produces a list, even if it only has one element. So

(map [ [a b c] -> a + b = c ] [1] [2] [3])

does produce [true]. Thus

(map [ [a b c] -> a + b = c ] [1 2] [2 3] [3 5])

will produce [true true]. reduce is helpful here,

reduce AND (map [ [a b c] -> a + b = c ] [1 2] [2 3] [3 5])

will produce a simple true by "anding" all the elements of the map output, and

reduce AND (map [ [a b c] -> a + b = c ] [1 2] [2 3] [3 6])

will produce a simple false.

huangapple
  • 本文由 发表于 2020年1月6日 20:53:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定