【问题标题】:How to map with scala constructor如何使用 scala 构造函数进行映射
【发布时间】:2017-08-02 01:10:25
【问题描述】:

我正在学习 Scala Coursera 课程中的函数式编程;我正在做关于霍夫曼编码树的练习。

这是表示霍夫曼树的代码

sealed abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree

我们假设它实现了一个接受List[(Char,Int)]并返回List[Leaf]的函数

这是我的代码:

def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = freqs.map(
    (c, i) => Leaf(c, i)
)

但是我收到了这个错误

谁能向我解释这段代码有什么问题?

【问题讨论】:

    标签: scala functional-programming type-mismatch


    【解决方案1】:

    这是您要查找的语法:

    def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = freqs.map {
        case (c, i) => Leaf(c, i)
    }
    

    由于您正在映射一个元组列表,如果您想在迭代时解包它们,您需要提供一个匹配的元组大小写。

    你也可以像这样解压你的元组:

    def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = freqs.map(tuple => {
       val (c, i) = tuple
       Leaf(c, i)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2019-11-23
      相关资源
      最近更新 更多