Thoughts Heap

A Blog by Roman Gonzalez.-

RSS
Nov
28th
Mon
permalink

Clojure’s repeatedly gotcha

When using Clojure’s repeatedly function to read lines from a terminal, or when trying to do IO of some sort, the behavior won’t be as expected

This is because repeatedly instead of calling the action n times, it generates a lazy seq for each time the action function gets called. Given that it is a lazy seq, if you don’t force the evaluation of the list, all but the first element will not be executed.

In order to avoid this, you have to use the dorun function, this is going to force evaluation for each element on a lazy seq, and it will discard the result of the seq altogether, this is because this function is expecting the action body to be for side-effects only

if you come from Haskell land, the idiom (dorun (repeatedly n body-fn)) would be the equivalent to call the function repeatM_.

An example:

  1. romanandreg posted this
blog comments powered by Disqus