# Do block syntax examples

**URL:** <https://discourse.julialang.org/t/do-block-syntax-examples/40757>\
**Category:** General Usage\
**Created:** [June 4, 2020, 7:34pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757 "2020-06-04T19:34:04Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![tbeason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tbeason/32/15898_2.png) [@tbeason](https://discourse.julialang.org/u/tbeason)\
**Post date:** [June 4, 2020, 7:34pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/1 "2020-06-04T19:34:04Z")

</div>

I know there are some people who are really big fans of the `do` block syntax for things like `map` etc. I am trying to get on board but it is usually never the first thing to come to mind when I’m writing code. The only instances where I’ve used it are exactly the ones given in the documentation. Would anybody be willing to just plop down a couple of cases where they’ve used the syntax? Doesn’t even need to be runnable code like a MWE, just copy paste so I can looksy.

Ref: [Functions · The Julia Language](https://docs.julialang.org/en/v1/manual/functions/#Do-Block-Syntax-for-Function-Arguments-1)

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [June 4, 2020, 7:39pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/2 "2020-06-04T19:39:43Z")

</div>

My most common use case is with [`open`](https://docs.julialang.org/en/v1/base/io-network/#Base.open), e.g.

```julia
open("path", "w") do io
    # something with io
end

```

Edit: Just realized that’s the example given in the docs so maybe not very helpful. [`tempdir`](https://docs.julialang.org/en/v1/base/file/#Base.Filesystem.mktempdir-Tuple%7BFunction,AbstractString%7D) is another one I use often:

```julia
mktempdir() do dir
    # something with the temp dir
end

```

---

<div class="post-metadata">

**Author:** ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)\
**Post date:** [June 4, 2020, 8:09pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/3 "2020-06-04T20:09:27Z")

</div>

I think I agree with you inasmuch as the do syntax always feels jumbled up to me. In fact, I find the “awkward” example from the cited documentation to be clearer than the “more clear” example using the do syntax. I think my brain expects the first argument to be the first argument, but instead I read what the first arg is, then learn that there’s this block which is actually the first arg and what I thought was first is really second (that’s the jumbled feeling). So I just store this away as a weird (to me) special case which has advantages I don’t presently grok.

---

<div class="post-metadata">

**Author:** ![pixel27](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pixel27/32/8902_2.png) [@pixel27](https://discourse.julialang.org/u/pixel27)\
**Post date:** [June 4, 2020, 8:16pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/4 "2020-06-04T20:16:46Z")

</div>

The “do” syntax is most useful when there is some cleanup that needs to be done after the operation. That is why using it with `open()` works well, **you** don’t have to worry about closing the file, the standard library is responsible for that. Same with `mktempdir()` where you want to delete the directory/file after you are done with it.

But of course not all functions in the base library have a need for the “do” syntax because there is no cleanup. So I guess when using a function, if it has some cleanup that you normally need to do, see if it can take a function as the first parameter and try to use that…if it makes sense.

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [June 4, 2020, 8:24pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/5 "2020-06-04T20:24:21Z")

</div>

MeshCat.jl uses the `do`-block syntax for animation frames, and I find it really convenient and readable in that case:

```julia
anim = Animation()

atframe(anim, 0) do
    settransform!(vis["/Cameras/default"], Translation(0., 0, 0))
end

atframe(anim, 30) do
    settransform!(vis["/Cameras/default"], Translation(0., 0, 1))
end

```

Ref: [Jupyter Notebook Viewer](https://nbviewer.jupyter.org/github/rdeits/MeshCat.jl/blob/master/notebooks/animation.ipynb#Building-an-Animation)

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [June 4, 2020, 8:40pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/6 "2020-06-04T20:40:59Z")

</div>

I cannot get this syntax. I’ve had it explained, but it doesn’t stick. Something is off with the word `do`. Do what? Do dir? Do io? Do the dishes? It doesn’t compute for me.

---

<div class="post-metadata">

**Author:** ![tkluck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkluck/32/15769_2.png) [@tkluck](https://discourse.julialang.org/u/tkluck)\
**Post date:** [June 4, 2020, 8:52pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/7 "2020-06-04T20:52:11Z")

</div>

> [@DNF](#):
>
> Something is off with the word `do` . Do what? Do dir? Do io? Do the dishes?

I agree it’s not very immediately clear unless you’re used to it. But maybe this example with `foreach` is helpful because it reads a bit more like a sentence:

```julia
items = ["Hello", "world!"]
foreach(items) do #= the following with =# the_item
    println(the_item)
end

```

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [June 4, 2020, 8:58pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/8 "2020-06-04T20:58:28Z")

</div>

I’ve had it explained, and then I think “ok, that makes sense”. But two days later it’s just gone.

---

<div class="post-metadata">

**Author:** ![tim.holy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tim.holy/32/52_2.png) [@tim.holy](https://discourse.julialang.org/u/tim.holy)\
**Post date:** [June 4, 2020, 9:19pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/9 "2020-06-04T21:19:16Z")

</div>

I had exactly the same experience as you, @DNF. Eventually something flipped and it became much more natural. Try thinking of it this way:

```julia
map(x -> x^2, list)

```

is the same as

```julia
f = function(x)
    x^2
end
map(f, list)

```

is the same as

```julia
map(list) do x
    x^2
end

```

EDIT: notice that the `do` syntax lines up with the `function(x)` syntax, so that the only difference is that the `do` syntax just avoids assigning the function to a named variable.

Now, this example is probably better written with `x->x^2`, but when it’s instead something more complicated, it can be nice to use the multiline syntax.

---

<div class="post-metadata">

**Author:** ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)\
**Post date:** [June 4, 2020, 9:21pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/10 "2020-06-04T21:21:26Z")

</div>

It’s not the automatic cleanup that throws me, it’s the syntax.

Using an anonymous function for the first argument or creating a function first and then passing its name in do the same thing and are (to me - I recognize the subjectivity here!) more readable.

I’m curious about the history of the do syntax.What languages use similar syntax?

---

<div class="post-metadata">

**Author:** ![tkluck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkluck/32/15769_2.png) [@tkluck](https://discourse.julialang.org/u/tkluck)\
**Post date:** [June 4, 2020, 9:31pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/11 "2020-06-04T21:31:20Z")

</div>

> [@klaff](#):
>
> What languages use similar syntax?

Ruby comes to mind: [Ruby From Other Languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/#:~:text=Iteration)

As far as I know it’s a quirk specific to Julia to lift the anonymous function over all the other function call arguments and insert it in the first position.

---

<div class="post-metadata">

**Author:** ![zweiglimmergneis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/zweiglimmergneis/32/7892_2.png) [@zweiglimmergneis](https://discourse.julialang.org/u/zweiglimmergneis)\
**Post date:** [June 4, 2020, 9:40pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/12 "2020-06-04T21:40:27Z")

</div>

Thanks for this discussion. I like the option to avoid long lines in programs. Now I realize that I can use the `do` for the first argument to `filter` like in

```julia
lv = ["CS", "AW", "W", "GS", "SAS"]
filter(lv) do x
       occursin("A", x)
end

```

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [June 4, 2020, 9:45pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/13 "2020-06-04T21:45:31Z")

</div>

Thanks. I will probably get it, then forget it again 😉 In seriousness, it’s probably just matter of using it actively a few times and then it’ll sink in. I do wish the syntax would reinforce the intuition a bit more, though.

---

<div class="post-metadata">

**Author:** ![tim.holy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tim.holy/32/52_2.png) [@tim.holy](https://discourse.julialang.org/u/tim.holy)\
**Post date:** [June 4, 2020, 9:47pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/14 "2020-06-04T21:47:14Z")

</div>

It helps if you line up the `do x` version with the `function(x)` version and then realize the only difference is not assigning it to a named variable.

---

<div class="post-metadata">

**Author:** ![EHBaozi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ehbaozi/32/14854_2.png) [@EHBaozi](https://discourse.julialang.org/u/EHBaozi)\
**Post date:** [June 4, 2020, 10:22pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/15 "2020-06-04T22:22:21Z")

</div>

For me, `do` blocks are used when I want to specify the context before carrying out the operation. Example: I would like to open a file, and _then_ think about what to do with the file, and thus

```julia
open(file, "w") do io
  # some operation
end

```

follows this mental model much better than writing `open(some_operation, file, "w")`. Similarly in the startup file we can do

```julia
atreplinit() do repl
  # stuff
end

```

as in, I specify the context (REPL is initializing) and then what I want to do within that context (eg. set up environment variables).

For python switchers, this usage pattern is quite similar to python’s `with` statement both conceptually and in their appearance (although Julia’s `do` block is far less restrictive), e.g.

```python
with open(file, 'r') as f:
  f.read()

```

---

<div class="post-metadata">

**Author:** ![heliosdrm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/heliosdrm/32/3851_2.png) [@heliosdrm](https://discourse.julialang.org/u/heliosdrm)\
**Post date:** [June 4, 2020, 10:25pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/16 "2020-06-04T22:25:06Z")

</div>

Since function names are often verbs (`map`, `open`, `filter`…), in most cases it helps thinking as if the keyword was **`doing`** instead of **`do`** , e.g.: “map this variable doing this…”, “open that file doing that…”.

(Exceptionally, in the cited cases of `foreach`, `atframe` or `atreplinit`, the actual keyword **`do`** looks better, because their name is rather adverbial.)

---

<div class="post-metadata">

**Author:** ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)\
**Post date:** [June 4, 2020, 10:28pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/17 "2020-06-04T22:28:58Z")

</div>

> [@EHBaozi](#):
>
> Example: I would like to open a file, and _then_ think about what to do with the file

That’s a helpful example! Thanks.

---

<div class="post-metadata">

**Author:** ![elron](https://avatars.discourse-cdn.com/v4/letter/e/4af34b/32.png) [@elron](https://discourse.julialang.org/u/elron)\
**Post date:** [June 4, 2020, 11:28pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/18 "2020-06-04T23:28:43Z")

</div>

`open` will close the file after calling the first argument, regardless of whether or not it’s called with `do` notation, right?  
The docs for `do` state  
“Create an anonymous function and pass it as the first argument to a function call.”  
ie, it’s just syntactic sugar; it’s not like, eg, a Python `with` construction.

I’m not arguing one way or another about the visual usefulness of `do`, just making sure I understood your statement (and the language) correctly. Did you just mean to point out that open was designed to take a callable so that it could ensure the file gets closed? That’s nice, but seems orthogonal to the choice to `do` or not to `do`

---

<div class="post-metadata">

**Author:** ![pixel27](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pixel27/32/8902_2.png) [@pixel27](https://discourse.julialang.org/u/pixel27)\
**Post date:** [June 4, 2020, 11:34pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/20 "2020-06-04T23:34:04Z")

</div>

> [@elron](#):
>
> `open` will close the file after calling the first argument, regardless of whether or not it’s called with `do` notation, right?

If you do:

```julia
io = open("filename.txt")
throw("Help, I'm the size of a bug.")
close(io)

```

`io` never get’s closed. Well when `io` get garbage collected, then the file will be close. With the `do` example:

```julia
open("filename.txt") do io
    throw("Help, I'm the size of a bug.")
end

```

The file get’s closed immediately.

---

<div class="post-metadata">

**Author:** ![elron](https://avatars.discourse-cdn.com/v4/letter/e/4af34b/32.png) [@elron](https://discourse.julialang.org/u/elron)\
**Post date:** [June 4, 2020, 11:37pm UTC](https://discourse.julialang.org/t/do-block-syntax-examples/40757/21 "2020-06-04T23:37:18Z")

</div>

but

```julia
f = io -> throw("Help, I'm the size of a bug.")
open(f, "filename.txt")

```

will also close the file, no?

[Next page](https://discourse.julialang.org/t/do-block-syntax-examples/40757.md?page=2)
