Hi all,
Scala provides .lift for various things like sets. I understand that *mathematically*, lift is an operator that moves a function from A => B to Collection[A] => Collection[B], or something like that.
map does that: List(1, 2, 3) map (_ *2)
but I thought it would be nice to apply it to functions. I decided to call it up and wrote some code like this
implicit def up[T, R](st: Seq[T])(f1: Function1[T, R]): Seq[R] = { st map f1 }
to pimp Function1. Ok, close but no cigar, my colleague had to fix it and got it working. I don't have the correct definition to hand but it worked and I could do stuff like (not tested here, but it did work)
val add1 = (a: Int) => a + 1
val double = (b: Int) => b * 2
val inp = List(1, 2, 3, 4)
add.up(double.up(inp))
to get
List(3, 5, 7, 9)
ie equivalent to
(inp map double) map add1 [ref 1]
but in a more set-based way (I have an SQL background which influences me a bit)
[1] can be traditionallly optimised to a single traversal:
inp map (double andThen add1)
So I was wondering if Scala has some mechanism that would, using my .up notation, allow the function application to be delayed to the final functional call in a chain ie. so that in
val x = f3.up(f2.up(f1.up(inp))) // maybe this can be written f3.up f2.up f1.up inp, not tried it
f1.up(inp) does not do anything but pass itself and its input 'inp' back to f2, which in turn passes itself and f1 and 'inp' back to f3, which can then say "I'm the last in the chain, so I'll compose myself and brothers upstream, and 'inp', to produce '(f3 andThen f2 andThen f1)' then map that over 'inp' ".
Main question: can a function detect it's last in the call chain and take a different action?
Small question: is scala's .lift in any way related to the mathematical version of lifting ( A => B --> F[A] => F[B] ) I mentioined above. It really doesn't look like it, either as a generalisation or specialisation of it.
Any other thoughts? - I rather like the cleanliness of .up, and
generalising it to muli-arg functions would seem to produce something
like zipWith.
cheers
jan