Scalaz为不同的ADT提供了一个名为fold的方法,如Boolean,Option[_],Validation[_, _],Either[_, _]等。该方法基本上接受与给定ADT的所有可能情况相对应的函数。换句话说,模式匹配如下所示:
x match {
case Case1(a, b, c) => f(a, b, c)
case Case2(a, b) => g(a, b)
.
.
case CaseN => z
}
等同于:
x.fold(f, g, ..., z)
下面是一些例子:
scala> (9 == 8).fold("fo
假设我在写:
sealed trait Status
object Error1 extends Status
case class Ok(x: Int) extends Status
def foo(opt: Option[Int]): Status = opt.fold(Error1)(x => Ok(x))
当我在REPL中尝试时,会得到一个错误:
scala> def foo(opt: Option[Int]): Status = opt.fold(Error1)(x => Ok(x))
<console>:11: error: type misma
下面,sumAllIf是尾部递归的,而sumAllFold不是。然而,sumAllIf实际上具有相同的实现。这是Scala编译器(或者Scala库)的一个缺点,还是我忽略了什么?
def maybeNext(in: Int): Option[Int] = if in < 10 then Some(in + 1) else None
// The Scala library implements Option.fold like this:
// @inline final def fold[B](ifEmpty: => B)(f: A => B): B =
// if
我有下一个代码
val listOption: List[Option[Int]] = List(1.some, none, 2.some)
我想折叠元素,我会写下一段代码
val result = listx.fold(0.some)((acc, el) => {
(acc, el) match {
case (Some(a), Some(b)) => Some(a + b)
case (Some(a), _) => Some(a)
case (_, Some(b)) => Some(b)
case _ => el
}
}
我试着简化一个真实的代码,但不会太多。
给定以下输入,f和g的实现只是示例,实数实现更为复杂
scala> val m = Map("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4)
m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3, d -> 4)
scala> val f : Int => Option[Int] = i =>
这是对一个远未完成的的后续。下面的所有代码在Scala控制台中编译并运行良好。
考虑以下抽象数据类型,以及它作为类型类型必须支持的操作:
trait SIG {
type XOrY
type X <: XOrY
type Y <: XOrY
}
trait SIGOps[Sig <: SIG] {
def makeX(s: String): Sig#X
def makeY(i: Int): Sig#Y
// the disjunction is enforced with that fold
def fold[T](xy: Sig#XOrY)(i
case class SomeObject(value: Int)
val start : List[Int] = List(1,2,3,5,6)
def findfour(start : List[Int]) : Option[SomeObject] = {
start.find(_ equals 4)
//.isNone(logger.info("Couldnt find a four!")). <--- native way to do this?
.map(SomeObject(_))
}
我有一个现有的调用链(比示例更健壮,但场景相同)
val y: Seq[Either[String, Int]]
case class Response(value: String)
val notFound = Response("Not Found")
val found = Response("Found")
val response: Response = y.lastOption
.map(_.fold(_ => notFound, _ => found))
.getOrElse(notFound)
我收到了一份名单。我想得到名单上的最后一个Either。然后,
我不知道fold和foldLeft在Scala中有什么区别。
的问题有一个关于排序的答案。这是可以理解的。但我仍然不明白为什么(来自REPL):
scala> Array("1","2","3").foldLeft(0)(_ + _.toInt)
res6: Int = 6
但这并不意味着:
scala> Array("1","2","3").fold(0)(_ + _.toInt)
<console>:8: error: value toInt is not a membe
我们需要从case类创建一个请求查询字符串。case类包含可选属性: case class Example(..., str: Option[String], ..) 如果选项存在,我们希望创建一个查询参数,否则不创建查询参数。像这样: match example.str {
case Some(s) => s"¶m_str=$s"
case _ => ""
} 由于它出现在许多地方,我想让它变得更通用: def option2String(optionString: Option[String], template: St
当我看到这个时,我正试图在scala上做些什么。假设我有一个清单,比如说
val list1:List[String]=List("test1","test2")
我有这样的东西
val list2:Option[List[String]]=Some(List("test1"))
我试着用我的手去找互联系统的方法
list2.getOrElse(List.empty).intersect(list1)
我希望结果是List("test1"),而不是得到一个空列表。我在这里错过了什么?
我对Scala非常陌生,在做了一些日志之后,我想返回一个SomeString或None,但是返回的类型似乎不一致。
(Option[String]).fold{
logger.info("Message append failed")
None
}{stuff=>
logger.info("Message appended")
Some(stuff)
}
返回的编译器错误是以下Expression of type Some
我有一个Hive对象,如下所示:
import 'package:hive/hive.dart';
part 'cartHiveModel.g.dart';
@HiveType(typeId: 0)
class CartModel extends HiveObject {
// for the product title
@HiveField(0)
late final String title;
// for checking the store id
@HiveField(1)
late final String storeID;
我在我的Scala应用程序中收到了一个UnexpectedNullableFound错误,我希望得到一些关于如何纠正这个错误的帮助。
错误:-
[error] application - Unable to log user in. An exception was thrown
java.lang.RuntimeException: Left(UnexpectedNullableFound(ColumnName(.language,Some(language))))
我要找的是这个函数:
def maybe[A, B](a: Option[A])(f: A => B)(g: () => B): B = a match
{
case Some(x) => f(x)
case None => g()
}
它在Haskell的前奏中,所以我认为它可能在Scala标准库中的某个地方,而我刚刚错过了它。我讨厌在项目中对它进行重新编码,所以我想知道是否有人知道它在哪里,或者它肯定不在那里。或者,有没有更好的方法来获得这个功能?
待办事项应用 class ToDoItem{
final String id;
final String title;
final Color color;
final int price;
final IconData icon;
final String todoListId;
const ToDoItem({
@required this.color,
@required this.id,
@required this.todoListId,
@required this.price,
@required this.