mmm*_*reg 2 python recursion scala
我希望有人可以在Scala中为我提供一些基本的代码帮助.我用Python编写了一些演示代码.
考虑元素列表,其中元素可以包含整数或其他元素的列表.我想递归检查这个结构并修改它,同时保持整体结构.
为了在python中表示这一点,我使每个'element'成为一个带有一个键的字典('i'表示项目).与该键对应的值是int或类似dicts的列表.从而,
lst = [{'i': 1}, {'i': 2}, {'i': [{'i': 5}, {'i': 6}]}, {'i': 3}]
def recurse(x):
if isinstance(x, list):
return [recurse(a) for a in x]
else:
if isinstance(x['i'], list):
return dict(i=[recurse(a) for a in x['i']])
else:
return dict(i=(x['i'] + 1))
print "Input:"
for i in lst:
print i
print "\nResult:\n%s" % recurse(lst)
>>>
Input:
{'i': 1}
{'i': 2}
{'i': [{'i': 5}, {'i': 6}]}
{'i': 3}
Result:
[{'i': 2}, {'i': 3}, {'i': [{'i': 6}, {'i': 7}]}, {'i': 4}]
Run Code Online (Sandbox Code Playgroud)
我理解这是一种奇怪的做法,但我提供的数据就是这样的结构.我认为我的问题是python允许你从同一个函数返回不同的类型,而我不相信Scala.
另外,对于记录,Scala元素表示为Elem(4)或Elem(List(Elem(3)...,所以我假设模式匹配可以稍微进入它).
Did*_*ont 11
我宁愿不称之为列表列表,因为这不会告诉这些列表包含什么.结构是一棵树,更确切地说是一棵绿叶树,其中只有叶子中有数据.那将是:
sealed trait Tree[+A]
case class Node[+A](children: Tree[A]*) extends Tree[A]
case class Leaf[+A](value: A) extends Tree[A]
Run Code Online (Sandbox Code Playgroud)
然后添加方法映射以对树中的每个值应用函数
sealed trait Tree[+A] {
def map[B](f: A => B): Tree[B]
}
case class Node[+A](children: Tree[A]*) extends Tree[A] {
def map[B](f : A => B) = Node(children.map(_.map(f)): _*)
}
case class Leaf[+A](value: A) extends Tree[A] {
def map[B](f: A => B) = Leaf(f(value))
}
Run Code Online (Sandbox Code Playgroud)
然后你的输入是:
val input = Node(Leaf(1), Leaf(2), Node(Leaf(5), Leaf(6)), Leaf(3))
Run Code Online (Sandbox Code Playgroud)
如果你打电话给input.map(_ + 1)你得到你的输出
由于varargs Tree [A]*,结果显示有点难看.您可以通过添加Node来改进override def toString = "Node(" + children.mkString(", ") + ")"
您可能只在一个地方更喜欢这个方法,无论是在课外,还是直接在树中.这里作为Tree中的一种方法
def map[B](f: A => B): Tree[B] = this match {
case Node(children @ _*) => Node(children.map(_.map(f)): _*)
case Leaf(v) => Leaf(f(v))
}
Run Code Online (Sandbox Code Playgroud)
像Python一样使用无类型的方式不是很像scala,但可能会完成.
def recurse(x: Any) : Any = x match {
case list : List[_] => list.map(recurse(_))
case value : Int => value + 1
}
Run Code Online (Sandbox Code Playgroud)
(将值直接放在列表中.带有键"i"的地图(字典)使其复杂化并强制接受编译器警告,因为我们必须强制执行无法检查的强制转换,即映射接受字符串作为键:案例图:Map [String,_])
case Elem(content: Any)与直接在List中放置值相比,使用声音给我带来的安全性更强,同时更加冗长,并且没有将其称为树和区分节点和叶子而不显着更加严格的安全性和清晰度.
| 归档时间: |
|
| 查看次数: |
867 次 |
| 最近记录: |