英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论