Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: why doesn't List[=>Int] work?

I've been working on learning the ins and outs of scala, and recently I've come across something I'm curious about.

As I understand, if I want to pass a block of code that is effectively lazily evaluated to a function, (without evaluating it on the spot) I could type:

def run(a: =>Int):Int = {...}

In this sense, the function run receives a block of code, that is yet to be evaluated, which it evaluates and returns the computed Int of. I then tried to extend this idea to the List data structure. Typing:

def run(a: List[=>Int]) = {...} 

This however, returns an error. I was wondering why this is disallowed. How, other than by this syntax can I pass a list of unevaluated blocks of code?

like image 965
Chris Grimm Avatar asked Jan 01 '13 04:01

Chris Grimm


2 Answers

=>Int is the syntax for by name parameters. =>Int is not a type, so it can't be used as a parameter to List. However, ()=>Int is a type. It's the type of nullary functions that return Int. So this works:

def run(a: List[()=>Int]) = {...} 
like image 197
Kim Stebel Avatar answered Nov 15 '22 03:11

Kim Stebel


by-name parameter is not a first-class type in Scala.

List[()=>Int] is one of the solution. otherwise, You can use following Lazy data structure.

  • https://gist.github.com/1164885
  • https://github.com/scalaz/scalaz/blob/v6.0.4/core/src/main/scala/scalaz/Name.scala#L99-107
  • https://github.com/scalaz/scalaz/blob/v7.0.0-M7/core/src/main/scala/scalaz/Name.scala#L37-L60
  • https://github.com/scala/scala/blob/v2.10.0/src/reflect/scala/reflect/internal/transform/Transforms.scala#L9-23
  • https://github.com/harrah/xsbt/blob/v0.12.1/compile/api/SafeLazy.scala
  • https://github.com/okomok/ken/blob/0.1.0/src/main/scala/com/github/okomok/ken/Lazy.scala
  • https://github.com/playframework/Play20/blob/2.1-RC1/framework/src/play/src/main/scala/play/api/libs/functional/Util.scala#L3-L11
like image 5
Kenji Yoshida Avatar answered Nov 15 '22 01:11

Kenji Yoshida