gpt4 book ai didi

scala - 如何在Scala中定义具有相同功能的功能列表?

转载 作者:行者123 更新时间:2023-12-04 13:38:54 26 4
gpt4 key购买 nike

在各种Lisps中,我可以创建一系列函数,就好像它们只是普通值一样:

(def ops [+ - * /])

然后,我可以再次遍历,就像它们只是正常值一样:
(doseq [op ops] // (doseq (op ops) is like for (op <- ops) in scala
(println (op 1 2 3 4)))

现在,我在Scala中尝试了一些尝试,但都失败了:
scala> List(+, -, *, /)
<console>:1: error: illegal start of simple expression
List(+, -, *, /)
^

scala> List[Double => Double](+, -, *, /)
<console>:1: error: illegal start of simple expression
List[Double => Double](+, -, *, /)
^

scala> List[Double => Double](+_, -_, *_, /_)
<console>:8: error: not found: value *
List[Double => Double](+_, -_, *_, /_)
^
<console>:8: error: not found: value /
List[Double => Double](+_, -_, *_, /_)
^

那么在Scala中定义功能/操作符列表的正确程序是什么?

最佳答案

问题在于这些函数是二进制运算符,即它们采用两个操作数并返回一个。因此,您必须使用:

List[(Double, Double) => Double](_ + _, _ - _, _ * _, _ / _)

关于scala - 如何在Scala中定义具有相同功能的功能列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com