LiveScript icon indicating copy to clipboard operation
LiveScript copied to clipboard

yield through pipe

Open unclechu opened this issue 9 years ago • 10 comments
trafficstars

Why I can't do something like this?:

new Promise (-> do it)
    |> yield

I get invalid callee on line 2 error.

unclechu avatar Jan 29 '16 21:01 unclechu

Because it's not a function call, basically.

vendethiel avatar Jan 29 '16 22:01 vendethiel

@vendethiel may be it should works different for keyword yield?

unclechu avatar Jan 29 '16 22:01 unclechu

Maybe we should add a specialcase for yield.

vendethiel avatar Jan 29 '16 23:01 vendethiel

@vendethiel it would be cool!

unclechu avatar Jan 30 '16 06:01 unclechu

I'm gonna try land #823 first, then think about this.

summivox avatar Jan 31 '16 22:01 summivox

#823 would change this issue's meaning, though, wrt pipew

vendethiel avatar Jan 31 '16 23:01 vendethiel

@vendethiel Why? Sure #823 is about something different, namely (yield ...) could evaluate to a function. My worry is these two might clash and not merge cleanly, so I want to address #823 first then this.

summivox avatar Jan 31 '16 23:01 summivox

ah no, it's true in Ls we require explicit _ placeholder... Seems good thus

vendethiel avatar Feb 01 '16 00:02 vendethiel

Ah I get you now. It's ambiguous what it pipes into. My concern is you cannot treat yield as just another function (otherwise you would have to write yield!)...

summivox avatar Feb 01 '16 00:02 summivox

This is the kinda hacky work around I've found.

require! {
    'co'            : start-coroutine
    'prelude-ls'    : { map }
}

sleep = (n) ->
    resolve, _  <-! new Promise _
    _           <-! setTimeout _, 500 * n

    console.log "Finishing sleep #{n}"
    resolve n

main = (func) ->
    *<-! start-coroutine
    try
        yield from func!
    catch {stack}?
        console.log "ERROR: #{stack}"

tee = (func, data) -->
    func data
    data

wait-for = (func, promise) -->* func yield promise

main !->*
    yield [1 to 3] |> map sleep |> wait-for -> it |> tee console.log |> map (+) 3 |> map sleep

The waitFor -> it being the yield "in" the pipe, it only works if its on the same line though as it exploits the fact that the rest of the line -> it |> tee console.log |> map (+) 3 |> map sleep becomes part of the function.

I also like how it reads as "wait for it"

And we get the output

Finishing sleep 1
Finishing sleep 2
Finishing sleep 3
[ 1, 2, 3 ]
Finishing sleep 4
Finishing sleep 5
Finishing sleep 6

DylanRJohnston avatar Jun 04 '16 07:06 DylanRJohnston