是否可以在scala中编写函数,该函数将采用任意深度嵌套的列表的列表并将其递归转换为平面列表?例如:
flatten(List(List(1), List(List(2), 3), 4))
Run Code Online (Sandbox Code Playgroud)
应该回来
List(1,2,3,4)
Run Code Online (Sandbox Code Playgroud)
我做了一些尝试,shapeless但没有效果:
object flatten extends (List ~> List) {
def apply[T](s: List[T]) = s.map {
case l: List[T] => apply(s)
case x => x
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我:
类型不匹配
找到:清单[任何]
必填:列表[T]
如果可以推导正确的类型(在示例List[Int]而不是List[Any]),也将很棒
我经常做这样的事情:
import cats.effect.Sync
import cats.implicits._
case class User(name: String)
case object Error extends Exception
def validate[F[_]: Sync](name: String): F[Either[Error, User]] = Sync[F].pure(User(name).asRight)
def doSomething[F[_]: Sync]: F[User] = for {
maybeUser <- validate("Name")
user <- maybeUser.fold(Sync[F].raiseError[User](_), Sync[F].pure(_))
} yield user
Run Code Online (Sandbox Code Playgroud)
简而言之,这意味着 if Eitheris leftthen use raiseError,如果它right只是返回值。
有没有更方便的“拆包” 方法Either?
functional-programming scala scala-cats tagless-final cats-effect
是否可以Nil为地图创建?
我的意思是类似的东西:
List() match {
case Nil => true
}
Run Code Online (Sandbox Code Playgroud)
但有地图:
Map() match {
case NilMap => true
}
Run Code Online (Sandbox Code Playgroud)
我尝试实现它,但遇到了麻烦:
object NilMap extends Map[Nothing, Nothin] {
def unapply[K,V](map: Map[K,V]): Option[Map[K,V]] =
if(map.isEmpty) Some(map) else None
}
Run Code Online (Sandbox Code Playgroud)
但id无法编译...
我正在尝试为hackerrank上的函数式编程解决Messy Medians问题。
我的解决方案(如下)太慢了。它几乎使测试用例超时。
@tailrec
def calculate(steps: List[Int], states: List[List[Int]]): List[Int] = {
steps match {
case x::xs =>
if(x > 0) {
states match { //apend state
case Nil => calculate(xs, List(x) :: states)
case y :: _ => calculate(xs, (x :: y) :: states)
}
} else {
calculate(xs, states.drop(-x-1).head :: states) //rollback state
}
case Nil => states
.reverse
.map { // calculate median
case List(x) => x
case xs => xs.sorted.apply(if (xs.length % …Run Code Online (Sandbox Code Playgroud)