Scala 中的 IEnumerable LINQ 等价物图表?

发布于 2024-12-14 20:26:06 字数 352 浏览 4 评论 0原文

可能的重复:
Scala 中的 LINQ 类似物

我正在寻找显示 IEnumerable 的 LINQ 方法在 Scala 中的等效项的图表:

  • 首先是 head
  • Select 是 map
  • SingleOrDefault 是...(我不知道)
  • ...等等

有谁知道这样的“翻译”表吗?

Possible Duplicate:
LINQ analogues in Scala

I am looking for chart which shows equivalents in Scala of LINQ methods for IEnumerable:

  • First is head
  • Select is map
  • SingleOrDefault is ... (I don't know)
  • ... and so on

Does anyone know anything of such "translate" table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

没有你我更好 2024-12-21 20:26:06

我只是列出了 Enumerable 中的函数的等效项。截至目前,这还不完整。我稍后会尝试更新更多内容。

xs.Aggregate(accumFunc)              -> xs.reduceLeft(accumFunc)
xs.Aggregate(seed, accumFunc)        -> xs.foldLeft(seed)(accumFunc)
xs.Aggregate(seed, accumFunc, trans) -> trans(xs.foldLeft(seed)(accumFunc))
xs.All(pred)                         -> xs.forall(pred)
xs.Any()                             -> xs.nonEmpty
xs.Any(pred)                         -> xs.exists(pred)
xs.AsEnumerable()                    -> xs.asTraversable // roughly
xs.Average()                         -> xs.sum / xs.length
xs.Average(trans)                    -> trans(xs.sum / xs.length)
xs.Cast<A>()                         -> xs.map(_.asInstanceOf[A])
xs.Concat(ys)                        -> xs ++ ys
xs.Contains(x)                       -> xs.contains(x) //////
xs.Contains(x, eq)                   -> xs.exists(eq(x, _))
xs.Count()                           -> xs.size
xs.Count(pred)                       -> xs.count(pred)
xs.DefaultIfEmpty()                  -> if(xs.isEmpty) List(0) else xs // Use `mzero` (from Scalaz) instead of 0 for more genericity
xs.DefaultIfEmpty(v)                 -> if(xs.isEmpty) List(v) else xs
xs.Distinct()                        -> xs.distinct
xs.ElementAt(i)                      -> xs(i)
xs.ElementAtOrDefault(i)             -> xs.lift(i).orZero // `orZero` is from Scalaz
xs.Except(ys)                        -> xs.diff(ys)
xs.First()                           -> xs.head
xs.First(pred)                       -> xs.find(pred) // returns an `Option`
xs.FirstOrDefault()                  -> xs.headOption.orZero
xs.FirstOrDefault(pred)              -> xs.find(pred).orZero
xs.GroupBy(f)                        -> xs.groupBy(f)
xs.GroupBy(f, g)                     -> xs.groupBy(f).mapValues(_.map(g))
xs.Intersect(ys)                     -> xs.intersect(ys)
xs.Last()                            -> xs.last
xs.Last(pred)                        -> xs.reverseIterator.find(pred) // returns an `Option`
xs.LastOrDefault()                   -> xs.lastOption.orZero
xs.LastOrDefault(pred)               -> xs.reverseIterator.find(pred).orZero
xs.Max()                             -> xs.max
xs.Max(f)                            -> xs.maxBy(f)
xs.Min()                             -> xs.min
xs.Min(f)                            -> xs.minBy(f)
xs.OfType<A>()                       -> xs.collect { case x: A => x }
xs.OrderBy(f)                        -> xs.sortBy(f)
xs.OrderBy(f, comp)                  -> xs.sortBy(f)(comp) // `comp` is an `Ordering`.
xs.OrderByDescending(f)              -> xs.sortBy(f)(implicitly[Ordering[A]].reverse)
xs.OrderByDescending(f, comp)        -> xs.sortBy(f)(comp.reverse)
Enumerable.Range(start, count)       -> start until start + count
Enumerable.Repeat(x, times)          -> Iterator.continually(x).take(times)
xs.Reverse()                         -> xs.reverse
xs.Select(trans)                     -> xs.map(trans) // For indexed overload, first `zipWithIndex` and then `map`.
xs.SelectMany(trans)                 -> xs.flatMap(trans)
xs.SequenceEqual(ys)                 -> xs.sameElements(ys)
xs.Skip(n)                           -> xs.drop(n)
xs.SkipWhile(pred)                   -> xs.dropWhile(pred)
xs.Sum()                             -> xs.sum
xs.Sum(f)                            -> xs.map(f).sum // or `xs.foldMap(f)`. Requires Scalaz.
xs.Take(n)                           -> xs.take(n)
xs.TakeWhile(pred)                   -> xs.takeWhile(pred)
xs.OrderBy(f).ThenBy(g)              -> xs.sortBy(x => (f(x), g(x))) // Or: xs.sortBy(f &&& g). `&&&` is from Scalaz.
xs.ToArray()                         -> xs.toArray // Use `xs.toIndexedSeq` for immutable indexed sequence.
xs.ToDictionary(f)                   -> xs.map(f.first).toMap // `first` is from Scalaz. When f = identity, you can just write `xs.toMap`.
xs.ToList()                          -> xs.toList // This returns an immutable list. Use `xs.toBuffer` if you want a mutable list.
xs.Union(ys)                         -> xs.union(ys)
xs.Where(pred)                       -> xs.filter(pred)
xs.Zip(ys, f)                        -> (xs, ys).zipped.map(f) // When f = identity, use `xs.zip(ys)`

某些功能没有直接等效的功能,但开发自己的功能相当容易。这里有一些这样的函数。

单个

def single[A](xs: Traversable[A]): A = {
  if(xs.isEmpty) sys error "Empty sequence!"
  else if(xs.size > 1) sys error "More than one elements!"
  else xs.head
}

SingleOrDefault

def singleOrDefault[A : Zero](xs: Traversable[A]): A = {
  if(xs.isEmpty) mzero
  else if(xs.size > 1) sys error "More than one elements!"
  else xs.head
}

加入

def join[A, B, K, R](outer: Traversable[A], inner: Traversable[B])
    (outKey: A => K, inKey: B => K, f: (A, B) => R): Traversable[R] = {
  for(o <- outer; i <- inner; if outKey(o) == inKey(i)) yield f(o, i)
}

GroupJoin

def groupJoin[A, B, K, R](outer: Traversable[A], inner: Traversable[B])
    (outKey: A => K, inKey: B => K, f: (A, Traversable[B]) => R): Traversable[R] = {
  for(o <- outer) yield {
    val zs = for(i <- inner; if outKey(o) == inKey(i)) yield i
    f(o, zs)
  }
}

注释

  1. 惯用语Scala,总体函数通常优于部分函数。因此,singlesingleOrDefault 的惯用实现将生成 Either[Exception, A] 类型的值,而不是 A >。例如,这里是 single 的精炼实现,它返回 Either[Exception, A]

    def single[A](xs: Traversable[A]): Either[Exception, A] = {
      if(xs.isEmpty) Left(new RuntimeException("空序列!"))
      else if(xs.size > 1) Left(new RuntimeException("多个元素!"))
      否则右(xs.head)
    }
    
  2. Scalaz 的 Zero/mzero 与 C# 的 default 值机制不太一样。具体可以参考这个 我之前就这个主题写过一篇文章。

  3. 您可以使用丰富我的库模式来达到与 C# 扩展方法相同的效果。请参阅了解详细信息。

I am only listing out the equivalents of functions from Enumerable<A>. This is incomplete as of now. I will try to update this later with more.

xs.Aggregate(accumFunc)              -> xs.reduceLeft(accumFunc)
xs.Aggregate(seed, accumFunc)        -> xs.foldLeft(seed)(accumFunc)
xs.Aggregate(seed, accumFunc, trans) -> trans(xs.foldLeft(seed)(accumFunc))
xs.All(pred)                         -> xs.forall(pred)
xs.Any()                             -> xs.nonEmpty
xs.Any(pred)                         -> xs.exists(pred)
xs.AsEnumerable()                    -> xs.asTraversable // roughly
xs.Average()                         -> xs.sum / xs.length
xs.Average(trans)                    -> trans(xs.sum / xs.length)
xs.Cast<A>()                         -> xs.map(_.asInstanceOf[A])
xs.Concat(ys)                        -> xs ++ ys
xs.Contains(x)                       -> xs.contains(x) //////
xs.Contains(x, eq)                   -> xs.exists(eq(x, _))
xs.Count()                           -> xs.size
xs.Count(pred)                       -> xs.count(pred)
xs.DefaultIfEmpty()                  -> if(xs.isEmpty) List(0) else xs // Use `mzero` (from Scalaz) instead of 0 for more genericity
xs.DefaultIfEmpty(v)                 -> if(xs.isEmpty) List(v) else xs
xs.Distinct()                        -> xs.distinct
xs.ElementAt(i)                      -> xs(i)
xs.ElementAtOrDefault(i)             -> xs.lift(i).orZero // `orZero` is from Scalaz
xs.Except(ys)                        -> xs.diff(ys)
xs.First()                           -> xs.head
xs.First(pred)                       -> xs.find(pred) // returns an `Option`
xs.FirstOrDefault()                  -> xs.headOption.orZero
xs.FirstOrDefault(pred)              -> xs.find(pred).orZero
xs.GroupBy(f)                        -> xs.groupBy(f)
xs.GroupBy(f, g)                     -> xs.groupBy(f).mapValues(_.map(g))
xs.Intersect(ys)                     -> xs.intersect(ys)
xs.Last()                            -> xs.last
xs.Last(pred)                        -> xs.reverseIterator.find(pred) // returns an `Option`
xs.LastOrDefault()                   -> xs.lastOption.orZero
xs.LastOrDefault(pred)               -> xs.reverseIterator.find(pred).orZero
xs.Max()                             -> xs.max
xs.Max(f)                            -> xs.maxBy(f)
xs.Min()                             -> xs.min
xs.Min(f)                            -> xs.minBy(f)
xs.OfType<A>()                       -> xs.collect { case x: A => x }
xs.OrderBy(f)                        -> xs.sortBy(f)
xs.OrderBy(f, comp)                  -> xs.sortBy(f)(comp) // `comp` is an `Ordering`.
xs.OrderByDescending(f)              -> xs.sortBy(f)(implicitly[Ordering[A]].reverse)
xs.OrderByDescending(f, comp)        -> xs.sortBy(f)(comp.reverse)
Enumerable.Range(start, count)       -> start until start + count
Enumerable.Repeat(x, times)          -> Iterator.continually(x).take(times)
xs.Reverse()                         -> xs.reverse
xs.Select(trans)                     -> xs.map(trans) // For indexed overload, first `zipWithIndex` and then `map`.
xs.SelectMany(trans)                 -> xs.flatMap(trans)
xs.SequenceEqual(ys)                 -> xs.sameElements(ys)
xs.Skip(n)                           -> xs.drop(n)
xs.SkipWhile(pred)                   -> xs.dropWhile(pred)
xs.Sum()                             -> xs.sum
xs.Sum(f)                            -> xs.map(f).sum // or `xs.foldMap(f)`. Requires Scalaz.
xs.Take(n)                           -> xs.take(n)
xs.TakeWhile(pred)                   -> xs.takeWhile(pred)
xs.OrderBy(f).ThenBy(g)              -> xs.sortBy(x => (f(x), g(x))) // Or: xs.sortBy(f &&& g). `&&&` is from Scalaz.
xs.ToArray()                         -> xs.toArray // Use `xs.toIndexedSeq` for immutable indexed sequence.
xs.ToDictionary(f)                   -> xs.map(f.first).toMap // `first` is from Scalaz. When f = identity, you can just write `xs.toMap`.
xs.ToList()                          -> xs.toList // This returns an immutable list. Use `xs.toBuffer` if you want a mutable list.
xs.Union(ys)                         -> xs.union(ys)
xs.Where(pred)                       -> xs.filter(pred)
xs.Zip(ys, f)                        -> (xs, ys).zipped.map(f) // When f = identity, use `xs.zip(ys)`

There is no direct equivalent of some functions, but it's fairly easy to roll your own. Here are some such functions.

Single:

def single[A](xs: Traversable[A]): A = {
  if(xs.isEmpty) sys error "Empty sequence!"
  else if(xs.size > 1) sys error "More than one elements!"
  else xs.head
}

SingleOrDefault:

def singleOrDefault[A : Zero](xs: Traversable[A]): A = {
  if(xs.isEmpty) mzero
  else if(xs.size > 1) sys error "More than one elements!"
  else xs.head
}

Join:

def join[A, B, K, R](outer: Traversable[A], inner: Traversable[B])
    (outKey: A => K, inKey: B => K, f: (A, B) => R): Traversable[R] = {
  for(o <- outer; i <- inner; if outKey(o) == inKey(i)) yield f(o, i)
}

GroupJoin:

def groupJoin[A, B, K, R](outer: Traversable[A], inner: Traversable[B])
    (outKey: A => K, inKey: B => K, f: (A, Traversable[B]) => R): Traversable[R] = {
  for(o <- outer) yield {
    val zs = for(i <- inner; if outKey(o) == inKey(i)) yield i
    f(o, zs)
  }
}

Notes:

  1. In idiomatic Scala, total functions are generally preferred over partial functions. So, idiomatic implementation of single and singleOrDefault would produce a value of type Either[Exception, A] instead of A. For example, here is refined implementation of single that returns Either[Exception, A].

    def single[A](xs: Traversable[A]): Either[Exception, A] = {
      if(xs.isEmpty) Left(new RuntimeException("Empty sequence!"))
      else if(xs.size > 1) Left(new RuntimeException("More than one elements!"))
      else Right(xs.head)
    }
    
  2. Scalaz's Zero/mzero are not quite same as C#'s default value mechanism. For details, you can refer to this post I wrote on this topic some time back.

  3. You can use enrich-my-library pattern to achieve the same effect as C#'s extension methods. Refer to this and this for details.

从此见与不见 2024-12-21 20:26:06

我对 C# 或 LINQ 一无所知,但这就是您要找的吗?

scala> val l = List(1, 2, 3, 4, 5)
l: List[Int] = List(1, 2, 3, 4, 5)

scala> l.head
res0: Int = 1

scala> l.headOption
res1: Option[Int] = Some(1)

scala> l.map(_.toString)
res2: List[java.lang.String] = List(1, 2, 3, 4, 5)

scala> l(1)
res3: Int = 2

没有方法可以获取元素或默认值,但这可以工作:

scala> scala.util.control.Exception.allCatch.opt(l(5)) getOrElse 0
res4: Int = 0

I don't know anything about C# or LINQ, but is this what you're looking for?

scala> val l = List(1, 2, 3, 4, 5)
l: List[Int] = List(1, 2, 3, 4, 5)

scala> l.head
res0: Int = 1

scala> l.headOption
res1: Option[Int] = Some(1)

scala> l.map(_.toString)
res2: List[java.lang.String] = List(1, 2, 3, 4, 5)

scala> l(1)
res3: Int = 2

There's no method to get an element or a default, but this will work:

scala> scala.util.control.Exception.allCatch.opt(l(5)) getOrElse 0
res4: Int = 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文