Wednesday, January 13, 2010

scheme like "apply" for scala

(define (m . args) args)
#;> (m 1 2 3)
(1 2 3)
;use apply to provide same arguments stored in a list
#;> (apply m (list 1 2 3))
(1 2 3)
We can do similar thing in scala using something like following...
scala> def m(as: Int*) = as
m: (as: Int*)Int*

scala> m(1, 2, 3)
res0: Int* = Array(1, 2, 3)

If you have a scala Sequence, you can use it as follow..

scala> m(List(1, 2, 3): _*)
res1: Int* = List(1, 2, 3)

scala> m(Seq(1, 2, 3): _*)
res2: Int* = List(1, 2, 3)
Its part of function call syntax as specified in §6.6 of the Scala Reference.

"The last argument in an application may be marked as a sequence argument, e.g. e: _*. Such an argument must correspond to a repeated parameter (§4.6.2) of type S* and it must be the only argument matching this parameter (i.e. the number of formal parameters and actual arguments must be the same). Furthermore, the type of e must conform to scala.Seq[T ], for some type T which conforms to S. In this case, the argument list is transformed by replacing the sequence e with its elements. When the application uses named arguments, the vararg parameter has to be specified exactly once."

No comments:

Post a Comment