Skip to main content
2 of 6
named the function, as the author of this challenge requested in the comments
ngn
  • 15.3k
  • 2
  • 43
  • 87

APL, 5 characters

f←/⍨⍳

This is a function. You can call it like this: f 5

How it works:

⍳n is the integers from 1 to n. Example: ⍳3 ←→ 1 2 3

/ means replicate. Each element from the right argument is repeated as many times as specified by its corresponding element from the left argument. Example: 2 0 3/'ABC' ←→ 'AACCC'

is the switch operator. When it occurs to the right of a function invoked with a single argument, the switch operator provides it as both left and right argument, so f⍨ A ←→ A f A. (It can also swap arguments: A f⍨ B ←→ B f⍨ A, hence "switch", but that's irrelevant to this solution.)

So, /⍨ is a (derived) function and is a function. A "train" of two functions in isolation forms a so-called atop. An atop with a single argument is equivalent to composition: (f g)A ←→ f g A, so g is applied to A, then f is applied to the result.

Bonus: the shortest I could come up with is f←(∊⌽-1-⍳¨)⍳, 12 characters.

ngn
  • 15.3k
  • 2
  • 43
  • 87