Skip to content

FR: verb to apply a function N times #41579

@BeastyBlacksmith

Description

@BeastyBlacksmith

There are different ways to express "apply function foo N times to x"

julia> using BenchmarkTools
julia> N = 10; x = 1; foo(x) = x + 1;
julia> @btime foldl(|>, Iterators.repeated($foo, $N), init=$x)
  0.988 ns (0 allocations: 0 bytes)
11

julia> @btime (fill($foo,$N)...)($x)
  6.034 μs (1 allocation: 80 bytes)
11

julia> @btime reduce(,repeat([$foo],$N))($x)
  1.811 μs (2 allocations: 160 bytes)
11

julia> @btime reduce(,Iterators.repeated($foo,$N))($x)
  2.182 μs (0 allocations: 0 bytes)
11

(collected from slack thread)
I think those are hard to remember and having an allocation free fast implementation in Base would be a good idea in my opinion.

The only names that come to my mind are:

  • apply(foo, N, x)
  • fold(foo, N)(x) (though having foldr, foldl and fold is probably too much)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions