Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "ChainRulesCore"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "0.2.0"
version = "0.2.1-DEV"

[compat]
julia = "^1.0"
Expand Down
23 changes: 22 additions & 1 deletion src/differentials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,24 @@ Base.iterate(::One, ::Any) = nothing
Thunk(()->v)
A thunk is a deferred computation.
It wraps a zero argument closure that when invoked returns a differential.

Calling that thunk, calls the wrapped closure.
`extern`ing thunks applies recursively, it also externs the differial that the closure returns.
If you do not want that, then simply call the thunk

```
julia> t = @thunk(@thunk(3))
Thunk(var"##7#9"())

julia> extern(t)
3

julia> t()
Thunk(var"##8#10"())

julia> t()()
3
```
"""
struct Thunk{F} <: AbstractDifferential
f::F
Expand All @@ -190,7 +208,8 @@ macro thunk(body)
return :(Thunk(() -> $(esc(body))))
end

@inline extern(x::Thunk) = x.f()
(x::Thunk)() = x.f()
@inline extern(x::Thunk) = extern(x())

Base.Broadcast.broadcastable(x::Thunk) = broadcastable(extern(x))

Expand All @@ -206,3 +225,5 @@ end
end

Base.conj(x::Thunk) = @thunk(conj(extern(x)))

Base.show(io::IO, x::Thunk) = println(io, "Thunk($(repr(x.f)))")
19 changes: 19 additions & 0 deletions test/differentials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,25 @@
@test conj(o) == o
end

@testset "Thunk" begin
@test @thunk(3) isa Thunk

@testset "show" begin
rep = repr(Thunk(rand))
@test occursin(r"Thunk\(.*rand.*\)", rep)
end

@testset "Externing" begin
@test extern(@thunk(3)) == 3
@test extern(@thunk(@thunk(3))) == 3
end

@testset "calling thunks should call inner function" begin
@test (@thunk(3))() == 3
@test (@thunk(@thunk(3)))() isa Thunk
end
end

@testset "No ambiguities in $f" for f in (+, *)
# We don't use `Test.detect_ambiguities` as we are only interested in
# the +, and * operations. We also would catch any that are unrelated
Expand Down