2016-02-27 36 views
0

我有以下斯卡拉代码来回答问题4(在清单上实现dropWhile,它将从列表前缀中删除元素,只要它们与谓词匹配)第3章Functional Programming In Scala将方法添加到列表并传递匿名参数

object Chapter3 { 

    sealed trait List[+A] 

    case object Nil extends List[Nothing] 
    case class Cons[+A](head: A, tail: List[A]) extends List[A] 

    object List { 

     def apply[A](as: A*): List[A] = 
      if (as.isEmpty) Nil 
      else Cons(as.head, apply(as.tail: _*)) 

     def dropWhile[A](l: List[A], f: A => Boolean): List[A] = 
      l match { 
       case Nil => sys.error("cannot drop from empty list") 
       case Cons(h, t) if f(h) => dropWhile(t, f) 
       case _ => l 
      } 

    } 

    def main(args : Array[String]) { 
     def smallerThanThree(i: Int): Boolean = i < 3 
     println(List.dropWhile(List(1, 2, 3, 4, 5), smallerThanThree)) 

     // How can I call this directly on the list with anonymous function like below? 
     println(List(1, 2, 3, 4, 5).dropWhile(i => i < 3)) 
     // => Should return List(3, 4, 5) or Cons(3, Cons(4, Cons(5, Nil))). 

    } 
} 

我想要做的是两方面的:列表对象(List(1,2,3,4,5).dropWhile([f: A => Boolean]))上

  1. 呼叫dropWhile而是采用List.dropWhile([List[A]], [f: A => Boolean])
  2. 传递,而不是限定的功能smallerThanThree并传递该匿名方法(i => i < 3)。

现在,这给出了错误:

error: value dropWhile is not a member of Main.List[Int]

而匿名函数不也行。当我做

println(List.dropWhile(List(1, 2, 3, 4, 5), i => i < 3)) 

它给人的错误:

error: missing parameter type

谁能解释,如果以上两点可以完成,如果是这样,怎么样?

回答

1

为了您能够在性状List的实例上调用dropWhile,该特征必须声明此函数。该对象同名包含此功能不会自动这种方法“添加”到性状的事实。

您可以轻松地通过改变特征定义添加这样的功能,以List特点:

sealed trait List[+A] { 
    def dropWhile(f: A => Boolean): List[A] = List.dropWhile(this, f) 
} 

然后,您建议的代码按预期工作。

至于传递一个匿名函数 - 在这种情况下,编译器不能推断出其自身的Int类型,所以你必须明确地写出类型,如下所示:

println(List.dropWhile(List(1, 2, 3, 4, 5), (i: Int) => i < 3)) 
+0

感谢您的帮助。要添加到你的答案,你实际上也可以对类似'i => i <3'的匿名函数进行类型干涉。如果签名(和实现)更改如下,则可以这样做:'def dropWhile [A](l:List [A])(f:A => Boolean):List [A]'。然后你可以改变trait中的方法:'def dropWhile(f:A => Boolean):List [A] = List.dropWhile(this)(f)'。您不必指定类型,可以使用'dropWhile'如下:'println(List(1,2,3,4,5).dropWhile(i => i <3))'。 –

相关问题