scala.collection.TraversableLike Scala Examples

The following examples show how to use scala.collection.TraversableLike. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Collections.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http.util

import scalaz.{NonEmptyList, OneAnd, \/}

import scala.collection.TraversableLike

object Collections {

  implicit final class `cdhuc TraversableOps`[A, Self](private val self: TraversableLike[A, Self])
      extends AnyVal {

    import collection.generic.CanBuildFrom

    def partitionMap[E, B, Es, That](f: A => E \/ B)(
        implicit es: CanBuildFrom[Self, E, Es],
        that: CanBuildFrom[Self, B, That]): (Es, That) = {
      val esb = es(self.repr)
      val thatb = that(self.repr)
      self foreach { a =>
        f(a) fold (esb.+=, thatb.+=)
      }
      (esb.result, thatb.result)
    }
  }

  implicit final class `cdhuc Nel Ops`[A](private val self: NonEmptyList[A]) extends AnyVal {
    def collect[B](f: A PartialFunction B): Option[NonEmptyList[B]] =
      self.list.collect(f).toNel
  }

  def toNonEmptySet[A](as: NonEmptyList[A]): OneAnd[Set, A] = {
    import scalaz.syntax.foldable._
    OneAnd(as.head, as.tail.toSet - as.head)
  }
} 
Example 2
Source File: package.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf
import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom

package object transaction {

  
  private[transaction] def sequence[A, B, This, That](
      seq: TraversableLike[Either[A, B], This],
  )(implicit cbf: CanBuildFrom[This, B, That]): Either[A, That] =
    seq collectFirst {
      case Left(e) => Left(e)
    } getOrElse {
      val b = cbf.apply()
      seq.foreach {
        case Right(a) => b += a
        case e @ Left(_) => sys.error(s"impossible $e")
      }
      Right(b.result())
    }
} 
Example 3
Source File: Dumpable.scala    From spark-riak-connector   with Apache License 2.0 5 votes vote down vote up
package com.basho.riak.spark.util

import com.basho.riak.client.core.operations.CoveragePlanOperation.Response.{CoverageEntry => KVCoverageEntry}
import com.basho.riak.client.core.query.timeseries.{CoverageEntry => TSCoverageEntry}
import com.basho.riak.client.core.util.HostAndPort

import scala.collection.TraversableLike

trait Dumpable {
  def dump(lineSep: String = "\n"): String = toString
}


object DumpUtils {

  def dump(hp: HostAndPort):String =
    hp.getHost + ":" + hp.getPort

  def dump(ce: KVCoverageEntry, lineSep: String): String = {
    s"host: ${ce.getHost}:${ce.getPort}" + lineSep +
      s"description: ${ce.getDescription}" + lineSep +
      "context: " + {ce.getCoverageContext match {
      case null => "null"
      case c => c.map("%02X" format _).mkString
    }}
  }

  def dump(ce: TSCoverageEntry, lineSep: String): String = {
    val lb = ce.isLowerBoundInclusive match {
      case true => "["
      case false => "("
    }

    val ub = ce.isUpperBoundInclusive match {
      case true => "]"
      case false => ")"
    }

    s"host: ${ce.getHost}:${ce.getPort}" + lineSep +
      s"range: $lb${ce.getLowerBound},${ce.getUpperBound}$ub" + lineSep +
      "description: " + ce.getDescription + lineSep +
      "context: " + {ce.getCoverageContext match {
      case null => "null"
      case c => c.map("%02X" format _).mkString
    }}
  }

  private def mkDump(o: Any, lineSep: String): String =
    o match {
      case d: Dumpable =>
        d.dump(lineSep)

      case ce: TSCoverageEntry =>
        DumpUtils.dump(ce, lineSep)

      case ce: KVCoverageEntry=>
        DumpUtils.dump(ce, lineSep)

      case h: HostAndPort =>
        DumpUtils.dump(h)
    }

  def dumpWithIdx[T, Repr](traversable: TraversableLike[T, Repr], lineSep: String): String =
    traversable.foldLeft("", 0) {
      (t :(String, Int), r) =>
        (
          t._1 +
            (
              t._1 match {
                case "" => ""
                case  _ => lineSep
              }
              ) +
            s"[${t._2}] " + mkDump(r, lineSep),
          t._2 +1
        )
    }._1

  def dump[T, Repr](traversable: TraversableLike[T, Repr], lineSep: String): String =
    traversable.foldLeft("") {
      (sb, r) =>
        (sb match {
          case "" =>
            ""

          case _ =>
            sb + lineSep
        }) + mkDump(r, lineSep)
    }
} 
Example 4
Source File: CollectionOps.scala    From Conseil   with Apache License 2.0 5 votes vote down vote up
package tech.cryptonomic.conseil.common.util

import scala.collection.TraversableLike
import cats.instances.option._
import cats.syntax.applicative._
import cats.syntax.apply._

import scala.concurrent.{ExecutionContext, Future}

object CollectionOps {

  
  implicit class BoundedAppication[T, R, Coll[A] <: TraversableLike[A, _]](list: Coll[T]) {
    def onBounds(f: (T, T) => R): Option[R] = applyOnBounds(list)(f)
  }

  // simplifies mapping of an embedded structure (Option[List[..]])
  implicit class ExtendedOptionalList[T](val value: Option[List[T]]) extends AnyVal {
    def mapNested(function: T => Option[T]): Option[List[T]] = value.map(_.flatMap(function(_)))
  }

  // simplifies mapping of an embedded structure (Future[List[..]])
  implicit class ExtendedFuture[T](val value: Future[List[T]]) extends AnyVal {
    def mapNested(function: T => Option[T])(implicit apiExecutionContext: ExecutionContext): Future[List[T]] =
      value.map(_.flatMap(function(_)))
  }
} 
Example 5
Source File: TraversableExtensions.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.infra

import scala.collection.TraversableLike
import scala.language.implicitConversions

object TraversableExtensions {

  implicit def traversable2Extended[A, Repr](t: TraversableLike[A, Repr]): ExtTraversable[A, Repr] = new ExtTraversable[A, Repr](t)

  class ExtTraversable[A, Repr](t: TraversableLike[A, Repr]) {

    // https://stackoverflow.com/questions/3912753/scala-remove-duplicates-in-list-of-objects#answer-3912995
    def distinctBy[R](keyFun: (A) => R): Repr = {
      t.filterNot{ var set = Set[R]()
        obj => val k = keyFun(obj); val b = set(k); set += k; b}
    }
  }
} 
Example 6
Source File: package.scala    From diffx   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill
import acyclic.skipped

import scala.annotation.compileTimeOnly
import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
import scala.language.experimental.macros
import scala.language.higherKinds
import com.softwaremill.diffx.DiffxSupport._

package object diffx extends DiffxSupport {
  implicit def traversableDiffxFunctor[F[_], A](implicit
      cbf: CanBuildFrom[F[A], A, F[A]],
      ev: F[A] => TraversableLike[A, F[A]]
  ): DiffxFunctor[F, A] =
    new DiffxFunctor[F, A] {}

  trait DiffxMapAtFunctor[F[_, _], K, T] {
    @compileTimeOnly(canOnlyBeUsedInsideIgnore("each"))
    def each(fa: F[K, T])(f: T => T): F[K, T] = sys.error("")
  }

  implicit def mapDiffxFunctor[M[KT, TT] <: Map[KT, TT], K, T](implicit
      cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]]
  ): DiffxMapAtFunctor[M, K, T] = new DiffxMapAtFunctor[M, K, T] {}

  implicit class DiffxEachMap[F[_, _], K, T](t: F[K, T])(implicit f: DiffxMapAtFunctor[F, K, T]) {
    @compileTimeOnly(canOnlyBeUsedInsideIgnore("each"))
    def each: T = sys.error("")
  }
} 
Example 7
Source File: TransmittableIterableCollections.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package transmitter

import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
import scala.language.higherKinds

trait TransmittableGeneralIterableCollections extends TransmittableDummy {
  this: Transmittable.type =>

  final implicit def traversable[B, I, R, V[T] >: Null <: TraversableLike[T, V[T]]]
    (implicit
        transmittable: Transmittable[B, I, R],
        cbfI: CanBuildFrom[V[B], I, V[I]],
        cbfR: CanBuildFrom[V[I], R, V[R]])
  : DelegatingTransmittable[V[B], V[I], V[R]] {
      type Delegates = transmittable.Type
    } =
    DelegatingTransmittable(
      provide = (value, context) =>
        if (value == null) null else value map { context delegate _ },
      receive = (value, context) =>
        if (value == null) null else value map { context delegate _ })
}

trait TransmittableIterableCollections extends TransmittableGeneralCollections {
  this: Transmittable.type =>

  final implicit def identicalTraversable
    [T: IdenticallyTransmittable, V[T] <: TraversableLike[T, V[T]]]
  : IdenticallyTransmittable[V[T]] = IdenticallyTransmittable()
} 
Example 8
Source File: TransmittableIterableCollections.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package transmitter

import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
import scala.language.higherKinds

trait TransmittableGeneralIterableCollections extends TransmittableDummy {
  this: Transmittable.type =>

  final implicit def traversable[B, I, R, V[T] >: Null <: TraversableLike[T, V[T]]]
    (implicit
        transmittable: Transmittable[B, I, R],
        cbfI: CanBuildFrom[V[B], I, V[I]],
        cbfR: CanBuildFrom[V[I], R, V[R]])
  : DelegatingTransmittable[V[B], V[I], V[R]] {
      type Delegates = transmittable.Type
    } =
    DelegatingTransmittable(
      provide = (value, context) =>
        if (value == null) null else value map { context delegate _ },
      receive = (value, context) =>
        if (value == null) null else value map { context delegate _ })
}

trait TransmittableIterableCollections extends TransmittableGeneralCollections {
  this: Transmittable.type =>

  final implicit def identicalTraversable
    [T: IdenticallyTransmittable, V[T] <: TraversableLike[T, V[T]]]
  : IdenticallyTransmittable[V[T]] = IdenticallyTransmittable()
} 
Example 9
Source File: ModifyMacroSupport.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.internal

import scala.annotation.compileTimeOnly
import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom

trait ModifyMacroSupport extends ModifyMacroFunctorSupport {
  implicit def traversableModifyFunctor[F[_], A](implicit
      cbf: CanBuildFrom[F[A], A, F[A]],
      ev: F[A] => TraversableLike[A, F[A]]
  ): ModifyFunctor[F, A] =
    new ModifyFunctor[F, A] {}

  trait ModifyMapAtFunctor[F[_, _], K, T] {
    @compileTimeOnly(canOnlyBeUsedInsideModify("each"))
    def each(fa: F[K, T])(f: T => T): F[K, T] = sys.error("")
  }

  implicit def mapModifyFunctor[M[KT, TT] <: Map[KT, TT], K, T](implicit
      cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]]
  ): ModifyMapAtFunctor[M, K, T] = new ModifyMapAtFunctor[M, K, T] {}

  implicit class ModifyEachMap[F[_, _], K, T](t: F[K, T])(implicit f: ModifyMapAtFunctor[F, K, T]) {
    @compileTimeOnly(canOnlyBeUsedInsideModify("each"))
    def each: T = sys.error("")
  }
} 
Example 10
Source File: ShellCompleter.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.exec.shell

import java.util

import com.flaminem.flamy.conf.FlamyContext
import com.flaminem.flamy.utils.CliUtils
import com.flaminem.flamy.utils.logging.Logging
import jline.console.completer.Completer

import scala.collection.JavaConversions._
import scala.collection.TraversableLike
import scala.collection.mutable.{Builder, ListBuffer}
import scala.util.control.NonFatal

object ShellCompleter {

  
class ShellCompleter(rootContext: FlamyContext) extends Completer with Logging {

  import ShellCompleter._

  val handler: CandidateListCompletionHandler = new CandidateListCompletionHandler()

  override def complete(buffer: String, cursor: Int, candidates: util.List[CharSequence]): Int = {
    handler.setPrintSpaceAfterFullCompletion(true)
    val args: Seq[String] = CliUtils.split(buffer.substring(0, cursor))
    val lastWord: String = args.lastOption.getOrElse("")
    try {
      val truncatedArgs: Seq[String] = args.dropRight(1)
      val cliArgs = CliArgs(truncatedArgs, lastWord)
      val Candidates(strings, shift) = new OptionCompleter(handler, rootContext).complete(cliArgs)
      candidates.addAll(strings.sorted)
      cursor - cliArgs.lastWord.length + shift
    }
    catch {
      case NonFatal(e) =>
        logger.debug("Exception caught during auto-completion", e)
        cursor - lastWord.length
    }
  }

} 
Example 11
Source File: NamedCollection.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.utils.collection.mutable

import com.flaminem.flamy.utils.Named

import scala.collection.generic.CanBuildFrom
import scala.collection.mutable.{Builder, ListBuffer}
import scala.collection.{TraversableLike, mutable}
import scala.language.implicitConversions


class NamedCollection[V <: Named] extends IndexedCollection[String, V] with TraversableLike[V, NamedCollection[V]] {
  override def newBuilder: mutable.Builder[V, NamedCollection[V]] = {
    new ListBuffer[V] mapResult{x => new NamedCollection(x)}
  }

  def this(namedItems: Traversable[V]) = {
    this
    this++=namedItems
  }

  def getIndexOf(value: V): String = value.getName.toLowerCase

}

object NamedCollection {

  def newBuilder[V <: Named](): Builder[V, NamedCollection[V]] = {
    new Builder[V, NamedCollection[V]]() {
      val buffer = new NamedCollection[V]()

      override def +=(elem: V): this.type = {
        buffer += elem
        this
      }

      override def clear(): Unit = {
        buffer.clear()
      }

      override def result(): NamedCollection[V] = {
        buffer
      }
    }
  }

  implicit def canBuildFrom[In <: Named, Out <: Named]: CanBuildFrom[NamedCollection[In], Out, NamedCollection[Out]] = {
    new CanBuildFrom[NamedCollection[In], Out, NamedCollection[Out]]() {
      override def apply(from: NamedCollection[In]): Builder[Out, NamedCollection[Out]] = newBuilder()
      override def apply(): Builder[Out, NamedCollection[Out]] = newBuilder()
    }
  }

} 
Example 12
Source File: TraversableLikeExtension.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.utils.collection

import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
import scala.collection.mutable.ListBuffer
import scala.language.higherKinds


  def splitBy[B](fun: A => B)(implicit bf: CanBuildFrom[T[A], A, T[A]]): Iterable[(B, T[A])] = {
    if(t.isEmpty){
      Nil
    }
    else {
      val buffer = new ListBuffer[(B, T[A])]()
      var groupBuilder = bf(t)
      var prevB: Option[B] = None
      t.foreach{
        a =>
          val b = Some(fun(a))
          if(prevB != b){
            if(prevB.isDefined){
              buffer += prevB.get -> groupBuilder.result()
            }
            prevB = b
            groupBuilder = bf(t)
          }
          groupBuilder += a
      }
      buffer += prevB.get -> groupBuilder.result()
      buffer.result()
    }
  }

} 
Example 13
Source File: ItemName.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.model.names

import com.flaminem.flamy.model.exceptions.FlamyException
import org.rogach.scallop.ValueConverter

import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
import scala.language.{higherKinds, implicitConversions}
import scala.reflect.runtime.universe._
import scala.util.{Failure, Success, Try}


  def tryParse(s: String): Try[ItemName] = {
    Try{
      SchemaName.parse(s)
      .orElse{
        TableName.parse(s)
      }
      .orElse{
        TablePartitionName.parse(s)
      }
      .getOrElse {
        throw new IllegalArgumentException("Wrong item name : " + s)
      }
    }
  }

  def tryParse(s: String, allowedTypes: Set[Class[_]]): Try[ItemName] = {
    tryParse(s).flatMap {
      case item if allowedTypes.contains(item.getClass) => Success(item)
      case item =>
        Failure(
          new IllegalArgumentException(
            s"Item $item is a ${item.getClass.getSimpleName}, " +
            s"but only the following item types are allowed: ${allowedTypes.map{_.getSimpleName}.mkString("[", ", ", "]")}"
          )
        )
    }
  }

  implicit def fromStringTraversableLike[T[Z] <: TraversableLike[Z, T[Z]]]
  (l: T[String])(implicit bf: CanBuildFrom[T[String], ItemName, T[ItemName]]) : T[ItemName] = {
    l.map{tryParse(_).get}
  }

  private def fromArgs(args: Seq[String]): Either[String, Option[List[ItemName]]] = {
    val tries: Seq[Try[ItemName]] = args.map{tryParse}
    if(tries.forall{_.isSuccess}){
      Right(Some(tries.map{_.get}.toList))
    }
    else {
      val firstFailureIndex = tries.indexWhere(_.isFailure)
      Left(s"Could not parse the item name ${args(firstFailureIndex)}")
    }
  }

  implicit val scallopConverterList: ValueConverter[List[ItemName]] = {
    new ValueConverter[List[ItemName]] {
      override def parse(s: List[(String, List[String])]): Either[String, Option[List[ItemName]]] = {
        s match {
          case l if l.nonEmpty => fromArgs(l.flatMap{_._2})
          case Nil => Right(None)
        }
      }
      override val tag: TypeTag[List[ItemName]] = typeTag[List[ItemName]]
      override val argType = org.rogach.scallop.ArgType.LIST
    }
  }

} 
Example 14
Source File: ItemFiles.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.model.files

import com.flaminem.flamy.model.names.ItemName
import com.flaminem.flamy.utils.logging.Logging

import scala.collection.generic.Growable
import scala.collection.mutable.ListBuffer
import scala.collection.{TraversableLike, mutable}


  def filterFileTypes(predicate: (ItemName, FileType)=>Boolean): ItemFiles[T] = {
    this.filter{
      case file => predicate(file.getItemName, file.fileType)
    }
  }

  override def toString: String = mm.values.toString

  override def +=(file: T): ItemFiles.this.type = {
    mm.addBinding(file.fileType, file)
    this
  }

  override def clear(): Unit = {
    mm.clear()
  }
} 
Example 15
Source File: TableDependencyCollection.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.parsing.model

import com.flaminem.flamy.model.names.TableName
import com.flaminem.flamy.utils.collection.mutable.IndexedCollection

import scala.collection.generic.CanBuildFrom
import scala.collection.mutable.ListBuffer
import scala.collection.{TraversableLike, mutable}


  def copy(): TableDependencyCollection = {
    val res = new TableDependencyCollection
    res ++= this
    res
  }

  def getTables: Iterable[TableDependency] = {
    super.getAllValues
  }

  override def getIndexOf(value: TableDependency): TableName = {
    value.fullName
  }

}

object TableDependencyCollection {

  implicit val canBuildFrom = new CanBuildFrom[TableDependencyCollection, TableDependency, TableDependencyCollection] {
    override def apply(from: TableDependencyCollection): mutable.Builder[TableDependency, TableDependencyCollection] = {
      apply()
    }
    override def apply(): mutable.Builder[TableDependency, TableDependencyCollection] = {
      new ListBuffer[TableDependency] mapResult{x => new TableDependencyCollection(x)}
    }
  }

  implicit class TableDependencyCollectionConvertible(s: Seq[TableDependency]) {
    def toTableDependencyCollection: TableDependencyCollection = {
      new TableDependencyCollection(s)
    }
  }

}