首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何模式匹配字符串中的第一个字符

如何模式匹配字符串中的第一个字符
EN

Stack Overflow用户
提问于 2018-06-01 04:21:24
回答 2查看 1.5K关注 0票数 0

我只是在学习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)
             ^
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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

票数 2
EN

Stack Overflow用户

发布于 2018-06-01 04:26:19

::仅为列表定义,虽然Strings可以隐式转换为Seq,但结果不是List -您可以使用toListSeq转换为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 _ => // ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50632210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档