我只是在学习scala,并将代码的出现作为练习。我知道模式匹配在Haskell中很流行,并希望在scala中也能做类似的事情。
def part1(visited: Set[Coord], current: Coord, directions: String): Set[Coord] = directions match {
case "^" :: tail => part1(visited + current, current.up, tail)
case "v" :: tail => part1(visited + current, current.down, tail)
case "<" :: tail => part1(visited + current, current.left, tail)
case ">" :: tail => part1(visited + current, current.right, tail)
case _ => visited + current // The string is empty
}
我尝试过使用数组或字符列表而不是字符串进行转换,但总是卡住了。我粘贴在上面的代码报告:
Day3.scala:8: error: constructor cannot be instantiated to expected type;
found : scala.collection.immutable.::[B]
required: Array[Char]
case '^' :: tail => part1(visited + current, current.up, tail)
^
发布于 2018-06-01 04:31:59
::
,也被称为Cons,是一个用于List
的构造器,它有一个头和一个尾。您有一个表示字符串的Array[Char]
,所以除非显式地转换为List[Char]
,否则不能使用列表语义。你能做的就是使用一个守卫:
def part1(visited: Set[Coord], current: Coord, directions: String): Set[Coord] =
directions match {
case x if x.startsWith("^") => part1(visited + current, current.up, x.tail)
case x if x.startsWith("v") => part1(visited + current, current.down, x.tail)
case x if x.startsWith("<") => part1(visited + current, current.left, x.tail)
case x if x.startsWith(">") => part1(visited + current, current.right, x.tail)
case _ => visited + current // The string is empty
}
注意:tail
来自IndexedSeqOptimized
,而不是直接来自String
。
发布于 2018-06-01 04:26:19
::
仅为列表定义,虽然String
s可以隐式转换为Seq
,但结果不是List
-您可以使用toList
将Seq
转换为List
。另外,使用单引号创建Char
而不是字符串:
directions.toList match {
case '^' :: tail => // ...
case 'v' :: tail => // ...
case '<' :: tail => // ...
case '>' :: tail => // ...
case _ => // ...
}
或者,您可以仅匹配headOption
(返回第一个字符或None
)的结果:
directions.headOption match {
case Some('^') => // ...
case Some('v') => // ...
case Some('<') => // ...
case Some('>') => // ...
case _ => // ...
}
https://stackoverflow.com/questions/50632210
复制相似问题