【问题标题】:Scala: type mismatch in function composition, found (Int, Int) => Seq[Int] require ? => Seq[Int]Scala:函数组合中的类型不匹配,发现 (Int, Int) => Seq[Int] 需要? => 序列[整数]
【发布时间】:2020-06-19 19:01:56
【问题描述】:

我正在尝试在脚本中编写 2 个函数,但遇到了我无法解决的类型不匹配问题。 这是示例代码:

def generate(start: Int, end: Int): Seq[Int] = (start until end).toSeq
def restrain(seq: Seq[Int]) = seq.dropWhile(_ < 20).takeWhile(_ < 60)

val com: (Int, Int) => Seq[Int] = (restrain _ compose generate)

通过在 REPL 中加载它:

:load test.sc

我收到以下错误:

       val com: (Int, Int) => Seq[Int] = (restrain _ compose generate)
                                                             ^
test.sc:1: error: type mismatch;
        found   : (Int, Int) => Seq[Int]
        required: ? => Seq[Int]

我做错了什么?

【问题讨论】:

  • 另外,请参阅this answer(即使它回答了不同的问题)。

标签: scala type-systems function-composition


【解决方案1】:

Function2[Int, Int, Seq[Int]]Function1[(Int, Int), Seq[Int]] 的类型不一样。 (generate _) 产生前者,而对于这种组合,您需要后者。试试:

restrain _ compose (generate _).tupled

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2020-08-12
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多