Back to Projections

Functions · Projections · Practice Question

Project a Built-In Operator

Sign in to track your progress

Question

Using projections only (no lambdas), create the following specialised functions:

  1. double — multiplies its argument by 2
  2. halve — divides its argument by 2
  3. above500 — returns 1b if its argument is greater than 500
  4. pad10 — right-pads a string to 10 characters with spaces

Then apply each to a suitable example.

Solution

double:   2*
halve:    %[;2]
above500: >[;500]
pad10:    10$

double 7        / 14
halve 80        / 40
above500 600    / 1b
above500 300    / 0b
pad10 "hello"   / "hello     "

Explanation

2* is a projection of * with its left argument fixed to 2. In q, 2* reads as "a function that multiplies 2 by its argument" — because * is commutative this is the same as "multiply argument by 2".

%[;2] fixes the right argument of % (divide). The empty first slot becomes the new argument:

%[10;2]    / 5f — ordinary call
%[;2][10]  / 5f — via projection, conceptually {x % 2}

(% always returns a float, hence 5f.)

>[;500] projects > with 500 as the right argument. When called with x, it evaluates x > 500.

10$ projects the Pad form of $: with an integer on the left and a string on the right, $ pads the string with spaces (or truncates it) to that length — 10$"hello" is "hello ". A negative width pads on the left: -10$"hi" is " hi".

Note that 2* uses q's infix shorthand — 2* is identical to *[2;] written in full. Both forms are valid; 2* is more idiomatic for simple numeric constants on the left.