【问题标题】:how to use scalaz IList如何使用 scalaz IList
【发布时间】:2016-12-15 09:58:08
【问题描述】:

scala.collection.immutable.List 定义了indexWhere,它返回满足谓词 p 的一般序列的第一个元素的索引,如果不存在,则返回 -1

def indexWhere(p: (A) ⇒ Boolean): Int

所以,我可以使用:

List("hello", "world").indexWhere(_.length > 10) // -1

但是,我更希望获得Option[Int]。我看到这是在scalaz.IList中实现的:

def indexWhere(f: A => Boolean): Option[Int]

如何使用scalaz.IList.indexWhere? 我尝试导入 scalaz,但仍然得到 -1。

import scalaz._
import std.list._
List("hello", "world").indexWhere(_.length > 10) // -1 instead of None

【问题讨论】:

    标签: scalaz


    【解决方案1】:
    val ilist = IList.fromList(List("hello", "world"))    
    ilist.indexWhere(_.length > 10)  // None
    ilist.indexWhere(_.length > 2)   // Some(0)
    

    【讨论】:

    • 谢谢。知道为什么 scalaz 不为 IList 提供隐式类,这样我们就可以避免实例化 Ilist(就像在 scalaz 的其他地方所做的那样,例如 List(List(1)).join)?
    • (他们本可以使用不同的方法名称,这是唯一的问题)
    • 我认为,这只是为了避免与相同的方法名称混淆。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多