当前位置: 首页>>代码示例>>Scala>>正文


Scala List类代码示例

本文整理汇总了Scala中scala.collection.immutable.List的典型用法代码示例。如果您正苦于以下问题:Scala List类的具体用法?Scala List怎么用?Scala List使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了List类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: CatalogueSpec

//设置package包名称以及导入依赖的类
import Domino.solution
import org.scalatest._

import scala.collection.immutable.List

class CatalogueSpec extends FlatSpec with Matchers {

  val catalogue = new Catalogue
  catalogue.add(Document("First document", 1999))
  catalogue.add(Document("Second document", 1999))
  catalogue.add(Document("Third document", 1999))
  catalogue.add(Document("AThird document", 1999))
  catalogue.add(Document("AThird document", 2000))

  "Catalogue getDocuments" should " return correct list" in {
    catalogue.getDocuments should equal(List(Document("First document", 1999),
      Document("Second document", 1999),
      Document("Third document", 1999),
      Document("AThird document", 1999),
      Document("AThird document", 2000))
    )
  }

  "Catalogue getSortedDocuments" should " return correct list" in {
    catalogue.getSortedDocuments should equal(List(Document("AThird document", 1999),
      Document("AThird document", 2000),
      Document("First document", 1999),
      Document("Second document", 1999),
      Document("Third document", 1999))
    )
  }

  "Catalogue getUniqueWords" should " return correct list" in {
    catalogue.getUniqueWords should equal(List("First", "document", "Second", "Third", "AThird"))
  }

  "Catalogue getUniqueWords2" should " return correct list" in {
    catalogue.getUniqueWords2 should equal(List("First", "document", "Second", "Third", "AThird"))
  }

  "Catalogue.getDocumentsCountByYear" should " return correct list" in {
    catalogue.getDocumentsCountByYear should equal(Map(2000 -> 1, 1999 -> 4))
  }

} 
开发者ID:nikshev,项目名称:simple-scala,代码行数:46,代码来源:CatalogueSpec.scala

示例2: MethodDescriptor

//设置package包名称以及导入依赖的类
package com.nitin.nizhawan.decompiler.method

import scala.collection.immutable.List


class MethodDescriptor(descriptor:String) {
   val extractParams = """(?<=\()(.*)(?=\))""".r
   val returnType = getType(descriptor.split("\\)")(1))
   val args = extractParams.findAllIn(descriptor).next.split(";").filter(!_.isEmpty).map(getType(_))
   def getType(typeSign:String) :String={
     println("g"+typeSign)
     (typeSign.trim.toCharArray.toList.dropWhile(_=='[')(0) match {
        case 'L' => new String(typeSign.trim.toCharArray.toList.dropWhile(_=='[').tail.toArray).split(";")(0).replaceAll("/",".")
        case 'B' => "boolean"
        case 'V' => "void"
        case 'I' => "int"
        case 'F' => "float"
        case _ => "H"
      } ) +
      typeSign.trim.toCharArray.toList.takeWhile(_=='[').map(_=>"[]").mkString("")
   }
} 
开发者ID:nitin-nizhawan,项目名称:jedi,代码行数:23,代码来源:MethodDescriptor.scala

示例3: UnknownPatternInterpreter

//设置package包名称以及导入依赖的类
package org.opencompare.formalizer.interpreters

import java.util.regex.Matcher

import org.opencompare.api.java.{Feature, Product, Value}

import scala.collection.immutable.List

class UnknownPatternInterpreter (
    validHeaders : List[String],
    regex : String,
    parameters : List[String],
    confident : Boolean)
    extends RegexPatternInterpreter(validHeaders, regex, parameters, confident) {

  override def createValue(s: String, matcher : Matcher, parameters : List[String], product : Product, feature : Feature) : Option[Value] = {
		 val value = factory.createNotAvailable()
		 Some(value)
  }

} 
开发者ID:Bastcloa,项目名称:testJenkins,代码行数:22,代码来源:UnknownPatternInterpreter.scala

示例4: P3

//设置package包名称以及导入依赖的类
package org.spandya

import scala.collection.immutable.List


class P3[T] {
  // get nth element of list with zero-indexing.
  def nth(n: Integer, list: List[T]): T ={
    if(list.length - 1 < n) {
      throw new IndexOutOfBoundsException
    }
    if(n < 0) {
      throw new IllegalArgumentException
    }

    if(n == 0) {
      return list.head
    }
    else {
      nth(n-1, list.tail)
    }
  }
} 
开发者ID:sameerpandya,项目名称:99scala,代码行数:24,代码来源:P3.scala

示例5: P2Test

//设置package包名称以及导入依赖的类
package org.spandya

import org.scalatest.FunSuite

import scala.collection.immutable.List


class P2Test extends FunSuite {

  val testObj = new P2[String]

  test("An empty array will return an exception") {
    val emptyArray = List[String]()
    assertThrows[NoSuchElementException](testObj.penultimate(emptyArray))
  }

  test("An array with one element can not have a penultimate element so it returns an exception") {
    val singleElementArray = List[String]("first")
    assertThrows[NoSuchElementException](testObj.penultimate(singleElementArray))
  }

  test("An array with two elements will return the first element") {
    val expected = "first"
    val twoElementArray = List[String](expected, "second")
    assert(expected.equals(testObj.penultimate(twoElementArray)))
  }

  test("An array with more than two elements will return the penultimate element") {
    val expected = "first"
    val twoElementArray = List[String]("zeroth", expected, "second")
    assert(expected.equals(testObj.penultimate(twoElementArray)))
  }
} 
开发者ID:sameerpandya,项目名称:99scala,代码行数:34,代码来源:P2Test.scala

示例6: P3Test

//设置package包名称以及导入依赖的类
package org.spandya

import org.scalatest.FunSuite

import scala.collection.immutable.List

class P3Test extends FunSuite{

  val testObj = new P3[Any]

  test("Given a number K and a list, if K < 0, then throw exception") {
    val emptyList = List[Any]()
    assertThrows[IllegalArgumentException](testObj.nth(Integer.valueOf(-1), emptyList))
  }

  test("Given a number K and a list of length < K, then throw exception") {
    val n = Integer.valueOf(1)
    val singleElementList = List[Any](true)
    assertThrows[IndexOutOfBoundsException](testObj.nth(n, singleElementList))
  }

  test("Given n=0 and a list of length >= 1, then return first element of list") {
    val n = Integer.valueOf(0)
    val expectedValue = false
    val list = List[Any](expectedValue, 1, 3.5d, "hello")

    assert(expectedValue.equals(testObj.nth(n, list)))
  }

  test("Given n=1 and a list of length >= 2, then return second element of list") {
    val n = Integer.valueOf(1)
    val expectedValue = Integer.valueOf(1)
    val list = List[Any](false, expectedValue, 3.5d, "hello")

    assert(expectedValue.equals(testObj.nth(n, list)))
  }

  test("Given n=3 and a list of length >= 4, then return fourth element of list") {
    val n = Integer.valueOf(3)
    val expectedValue = "hello"
    val list = List[Any](false, 1, 3.5d, expectedValue)

    assert(expectedValue.equals(testObj.nth(n, list)))
  }

} 
开发者ID:sameerpandya,项目名称:99scala,代码行数:47,代码来源:P3Test.scala

示例7: RemoveDuplicates

//设置package包名称以及导入依赖的类
package com.pktippa
import scala.collection.immutable.List

object RemoveDuplicates {
  def main(args: Array[String]) {
    // Read input from command line
    val input:String = readLine();
    // Converting given input into List of characters
    var list = input.toList;
    // Calling distinct method in list to get unique characters in list
    // Build string from list of characters
    print(list.distinct.mkString);
  }
} 
开发者ID:pk-hackerrank,项目名称:hr-funcprog,代码行数:15,代码来源:RemoveDuplicates.scala

示例8: CutDS

//设置package包名称以及导入依赖的类
package comp.bio.aging.crispr

import org.apache.spark.api.java.StorageLevels
import org.apache.spark.rdd.RDD
import org.bdgenomics.adam.models.{ReferencePosition, ReferenceRegion}
import org.bdgenomics.adam.rdd.contig.NucleotideContigFragmentRDD
import comp.bio.aging.playground.extensions._
import scala.collection.immutable.{List, Nil}

object CutDS{
  //for Blunt edges
  def apply(guide: String, top: ReferencePosition): CutDS = new CutDS(guide, top, top)
}


case class CutDS(guide: String, top: ReferencePosition, bottom: ReferencePosition)
{
  lazy val leftishCut: ReferencePosition =  if(top.pos <= bottom.pos) top else bottom
  lazy val rightishCut: ReferencePosition = if(top.pos >= bottom.pos) top else bottom

  def leftArm(length: Long, canOverlap: Boolean = true): ReferenceRegion = {
    ReferenceRegion(leftishCut.referenceName,
      leftishCut.pos - length,
      (if(canOverlap) rightishCut else leftishCut).pos,
      strand = leftishCut.strand)
  }

  def rightArm(length: Long, canOverlap: Boolean = true): ReferenceRegion = {
    ReferenceRegion(rightishCut.referenceName,
      (if(canOverlap) leftishCut else rightishCut).pos,
      rightishCut.pos + length,
      strand = rightishCut.strand)
  }

  def arms(length: Long): List[ReferenceRegion] = arms(length, length)

  def arms(leftLength: Long, rightLength: Long) = List(leftArm(leftLength), rightArm(rightLength))

  def armsRegion(leftLength: Long, rightLength: Long): ReferenceRegion = {
    ReferenceRegion(top.referenceName,
      leftishCut.pos - leftLength,
      rightishCut.pos + rightLength,
      strand = top.strand)
  }

  def knockin(regionSeq: String, region: ReferenceRegion, leftLength: Long, rightLength: Long, overlap: Boolean): KnockIn = {
    val left = leftArm(leftLength, overlap)
    val right = rightArm(rightLength, overlap)
    val leftSeq = regionSeq.take(left.length().toInt)
    val rightSeq = regionSeq.takeRight(right.length().toInt)
    KnockIn(guide, leftSeq, left,  rightSeq, right)
  }

  def positive(length: Long): Boolean = (leftishCut.pos - length) >= 0

}

case class KnockIn(guide: String, leftArm: String, leftArmRegion: ReferenceRegion, rightArm: String, rightArmRegion: ReferenceRegion) 
开发者ID:antonkulaga,项目名称:CRISPR,代码行数:59,代码来源:KnockIn.scala

示例9: armsGuided

//设置package包名称以及导入依赖的类
package comp.bio.aging.crispr

import org.apache.spark.api.java.StorageLevels
import org.apache.spark.rdd.RDD
import org.bdgenomics.adam.models.{ReferencePosition, ReferenceRegion}
import org.bdgenomics.adam.rdd.contig.NucleotideContigFragmentRDD
import comp.bio.aging.playground.extensions._
import scala.collection.immutable.{List, Nil}



trait HomologyArms {

  def armsGuided(fragmentRDD: NucleotideContigFragmentRDD,
           guidedCats: RDD[(String, List[CutDS])],
           left: Long, right: Long, avoidSites: Set[String] = Set.empty, allowOverlap: Boolean = true): RDD[KnockIn] = {
    arms(fragmentRDD, guidedCats.values.flatMap(f=>f), left, right, avoidSites, allowOverlap)
  }

  def arms(fragmentRDD: NucleotideContigFragmentRDD,
           cuts: RDD[CutDS],
           left: Long, right: Long, avoidSites: Set[String] = Set.empty, allowOverlap: Boolean = true): RDD[KnockIn] = {

    val positiveCuts: RDD[(ReferenceRegion, CutDS)] = cuts.filter(_.positive(left)).map{
      case (cut) => cut.armsRegion(left, right) -> cut
    }.persist(StorageLevels.MEMORY_AND_DISK)

    val extracted: RDD[(ReferenceRegion, String)] = fragmentRDD.extractRegions(positiveCuts.keys.collect().toList)
      .filter{
        case (_, str) => !avoidSites.exists( s=> str.contains(s))
      }
    val joined: RDD[(ReferenceRegion, (CutDS, String))] = positiveCuts.join(extracted) //region,guide, value
    joined.map{
      case (region, (cut, regionSeq)) => cut.knockin(regionSeq, region, left, right, allowOverlap)
    }
  }
} 
开发者ID:antonkulaga,项目名称:CRISPR,代码行数:38,代码来源:HomologyArms.scala

示例10: buildCopyContext

//设置package包名称以及导入依赖的类
package fr.acinq.eclair.gui.utils

import javafx.event.{ActionEvent, EventHandler}
import javafx.scene.control.{ContextMenu, MenuItem}
import javafx.scene.input.{Clipboard, ClipboardContent}

import scala.collection.immutable.List


  def buildCopyContext (actions: List[CopyAction]): ContextMenu = {
    val context = new ContextMenu()
    for (action <- actions ) {
      val copyItem = new MenuItem(action.label)
      copyItem.setOnAction(new EventHandler[ActionEvent] {
        override def handle(event: ActionEvent) = copyToClipboard(action.value)
      })
      context.getItems.addAll(copyItem)
    }
    context
  }

  def copyToClipboard (value: String) = {
    val clipContent = new ClipboardContent
    clipContent.putString(value)
    clip.setContent(clipContent)
  }
} 
开发者ID:viacoin,项目名称:eclair,代码行数:28,代码来源:ContextMenuUtils.scala

示例11: KMeansPipeLineTest

//设置package包名称以及导入依赖的类
package com.knoldus.pipeline

import org.apache.spark.sql.{DataFrame, SQLContext}
import org.apache.spark.{SparkConf, SparkContext}
import org.scalatest.FunSuite

import scala.collection.immutable.List

class KMeansPipeLineTest extends FunSuite {
  val kMeans = new KMeansPipeLine()
  val conf = new SparkConf().setAppName("K-means-pipeline-test").setMaster("local[4]")
  val sc = new SparkContext(conf)
  val sqlContext = new SQLContext(sc)
  val input = sqlContext.createDataFrame(Seq(
    ("[email protected]", 12000,"M"),
    ("[email protected]", 43000,"M"),
    ("[email protected]", 5000,"F"),
    ("[email protected]", 60000,"M")
  )).toDF("email", "income","gender")

  val predictionResult = kMeans.predict(sqlContext,input,List("gender","email"),2,10)
  test("should return data frame") {
    predictionResult.show()
    predictionResult.isInstanceOf[DataFrame]
    sc.stop()
  }

} 
开发者ID:knoldus,项目名称:k-means-pipeline,代码行数:29,代码来源:KMeansPipeLineTest.scala

示例12: ZipfianStream

//设置package包名称以及导入依赖的类
package testbed.testdata

import breeze.stats.distributions.ZipfDistribution
import testbed.Numpy
import testbed._
import TestStream.fromCSV

import scala.collection.immutable.{Seq, List}

class ZipfianStream[K](values: Stream[Seq[K]], name: String, params: List[Parameter])
  extends TestStream[K](values, name, params){

}

object ZipfianStream{
  
  def apply[K](coefficient: Double, chunkSize: Int, chunks: Int = 1, name: String, pathToPython: String = "/usr/bin/python")
                (implicit intToK: Int => K) = {

    val params = List(("Zipf coefficient", coefficient))

    def fromBreeze = {
      val distribution: ZipfDistribution = new ZipfDistribution(chunks * chunkSize, coefficient)
      val values = new Iterator[Seq[K]] {
        var numChunksGenerated = 0

        override def hasNext: Boolean = numChunksGenerated < chunks

        override def next(): Seq[K] = {
          numChunksGenerated += 1
          distribution.drawMany(chunkSize).toList.map(intToK)
        }
      }.toStream

      new TestStream[K](values, name, params)
    }

    def fromNumpy(np: Numpy[TestStream[Int]]) = {
      val numpyExpression = s"np.random.zipf($coefficient, $chunks * $chunkSize)"
      val bufferName = "np_zipf_gen_buff.csv"
      val resultReader = {pathToCSV: String => fromCSV[Int](pathToCSV, chunks, name)}
      val numpyResult = np.getResult(numpyExpression, bufferName, resultReader)

      new TestStream[K](numpyResult.values.map(_.map(intToK)), numpyResult.name, params)
    }

    require(chunkSize * chunks <= Int.MaxValue, "Only Int.MaxValue elements supported.")

    val np = new Numpy[TestStream[Int]](pathToPython)

    if(np.isInstalled)
      fromNumpy(np)
    else
      fromBreeze
  }
} 
开发者ID:bethge,项目名称:sketching-testbed,代码行数:57,代码来源:ZipfianStream.scala

示例13: AgentEpayeRegistrationRepositoryISpec

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentepayeregistration.repository

import uk.gov.hmrc.agentepayeregistration.controllers.BaseControllerISpec
import uk.gov.hmrc.agentepayeregistration.models.{Address, AgentReference, RegistrationRequest}

import scala.collection.immutable.List
import scala.concurrent.ExecutionContext.Implicits.global

class AgentEpayeRegistrationRepositoryISpec extends BaseControllerISpec {
  private lazy val repo = app.injector.instanceOf[AgentEpayeRegistrationRepository]

  val postcode = "AB11 AA11"
  val addressLine1 = "Address Line 1"
  val addressLine2 = "Address Line 2"
  val addressLine3 = Some("Address Line 3")
  val addressLine4 = Some("Address Line 4")
  val regAddress = Address(addressLine1, addressLine2, addressLine3, addressLine4, postcode)

  val agentName = "Agent Name"
  val contactName = "Contact Name"
  val telephoneNumber = Some("0123456789")
  val faxNumber = Some("0123456780")
  val emailAddress = Some("[email protected]")
  val regDetails = RegistrationRequest(agentName, contactName, telephoneNumber, faxNumber, emailAddress, regAddress)

  override def beforeEach() {
    super.beforeEach()
    await(repo.ensureIndexes)
  }

  "AgentEpayeRegistrationRepository" can {

    "create a RegistrationDetails record" in {
      await(repo.find("agentName" -> agentName)) shouldBe List.empty

      val result = await(repo.create(regDetails))

      result shouldBe AgentReference("HX2000")

      await(repo.find("agentName" -> agentName)).head should have(
        'agentReference (AgentReference("HX2000")),
        'registration (regDetails)
      )
    }

    "create a unique Agent PAYE Reference code" in {
      await(repo.create(regDetails))
      await(repo.create(regDetails))
      await(repo.create(regDetails))

      val results = await(repo.find("agentName" -> agentName))

      results.size shouldBe 3

      results.head.agentReference shouldBe AgentReference("HX2000")
      results.drop(1).head.agentReference shouldBe AgentReference("HX2001")
      results.last.agentReference shouldBe AgentReference("HX2002")
    }
  }
} 
开发者ID:hmrc,项目名称:agent-epaye-registration,代码行数:61,代码来源:AgentEpayeRegistrationRepositoryISpec.scala


注:本文中的scala.collection.immutable.List类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。