我是HS的大四学生,也是函数式编程和Scala的新手。我在Scala中尝试了几个构造,并需要一些返回响应的指导。
//Defined a tuple
scala> val x =(2.0, 3.0, 1)
x: (Double, Double, Int) = (2.0,3.0,1)
//This made sense to me. Result is a list of values that are of type Ints
scala> x.productIterator.dropWhile(_.isInstanceOf[Double]).toList
res1: Lis
考虑使用+:向序列添加一个元素(从左边):
scala> val cl = Seq(1,2,3)
scala> 5 +: cl
res2: Seq[Int] = List(5, 1, 2, 3)
集合的等效性(如果有的话)是什么?
scala> val s = Set(1,2,3)
scala> 5 +: s
<console>:9: error: value +: is not a member of scala.collection.immutable.Set[Int]
5 +: s
scala> 5.toInt +
我在2.9.1和2.10每晚得到了不同的行为--是什么改变了?
Welcome to Scala version 2.9.1.final (OpenJDK Client VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
scala> Some(3) map (x => List(x, -x)) flatten
res0: List[Int] = List(3, -3)
对比:
Welcome to Scala version 2.10.0
我在Scala中有一个字符列表:
val a = "(i am(a? list) of(/ chars in )Scala)".toList
我想找到第一个‘)的位置,并将其从列表中删除。我怎么能这么做?
我所做的(但没有起作用):
val position = a.tail.indexOf(')')
a.drop(position)
并在a.take(position)上试了一下。我发现drop和take方法并不适合我所需要的东西。我希望该方法的工作原理如下:
input: (i am(a? list) of(/ chars in )Scala)
outp
package com.listbuffer.ex
import scala.collection.mutable.ListBuffer
object IUEReclass{
def main(args: Array[String]) {
val codes = "XY|AB"
val codeList = codes.split("|")
var lb = new ListBuffer[String]()
codeList.foreach(lb += "XYZ")
val l
当我写的时候
println(List[String Either Int](Left("Boom"), Right(42)).flatten)
编译器抱怨说
ScalaFiddle.scala:16: error: No implicit view available from Either[String,scala.this.Int] => collection.this.GenTraversableOnce[B].
println(List[String Either Int](Left("Boom"), Right(42)).flatten)
我正在使用scala尝试一些基本的逻辑。我尝试了下面的代码,但它会引发错误。
scala> val data = ("HI",List("HELLO","ARE"))
data: (String, List[String]) = (HI,List(HELLO, ARE))
scala> data.flatmap( elem => elem)
<console>:22: error: value flatmap is not a member of (String, List[String])
有人有关于如何在列表中使用andThen的例子吗?我注意到andThen是为List定义的,但是文档没有一个示例来说明如何使用它。
我的理解是,f andThen g表示执行函数f,然后执行函数g。函数g的输入是函数f的输出,这是正确的吗?
问题1-我编写了以下代码,但我不明白为什么要使用andThen,因为我可以使用map.实现相同的结果。
scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)
//simple function that increments value of element of lis
问题是:
我打算从函数中检索(Int,Int)对象,但是我不知道如何获得第二个元素。我尝试了以下命令,以便检索第二个值,或将其转换为Seq或List,但没有结果。
scala> val s = (1,2)
s: (Int, Int) = (1,2)
scala> s(1)
<console>:9: error: (Int, Int) does not take parameters
s(1)
^
scala> val ss = List(s)
ss: List[(Int, Int)] = List((1