Skip to content

Instantly share code, notes, and snippets.

@jlapeyre
Last active September 24, 2016 19:11
Show Gist options
  • Save jlapeyre/b93bead293f903b6afb1cc5d4bd14d13 to your computer and use it in GitHub Desktop.
Save jlapeyre/b93bead293f903b6afb1cc5d4bd14d13 to your computer and use it in GitHub Desktop.
generate code for a random walk step in `n` dimensions
# See the first comment for an explanation
using Lazy
function walkifs(dim)
conditions = Any[]
actions = Any[]
for i in 1:(2*dim-1)
push!(conditions, :( dir == $i ))
end
for i in 1:dim
sym = QuoteNode(Symbol("x",i))
push!(actions, :($sym += dx))
push!(actions, :($sym -= dx))
end
exprs = collect(riffle(conditions, actions))
push!(exprs, actions[end])
buildif(exprs...)
end
# e.g
"""
```julia
julia> walkifs(2)
:(if dir == 1
:x1 += dx
else
if dir == 2
:x1 -= dx
else
if dir == 3
:x2 += dx
else
:x2 -= dx
end
end
end)
```
"""
@jlapeyre
Copy link
Author

This gist depends on buildif.jl

julia> walkifs(2)
:(if dir == 1
        :x1 += dx
    else 
        if dir == 2
            :x1 -= dx
        else 
            if dir == 3
                :x2 += dx
            else 
                :x2 -= dx
            end
        end
    end)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment