Functions · Default Arguments · Practice Question
Simulate a Default Argument With a Null Check
Question
Write a function topN that:
- Takes a table
tand an optional countn - Returns the first
nrows oft, sorted bypricedescending - Defaults to 5 rows when
nis not supplied (i.e. the caller passes0N)
Solution
topN:{[t; n]
n: $[null n; 5; n];
select[n; >price] from t
}
trade:([] sym:`AAPL`MSFT`GOOG`AAPL`MSFT; price:185.5 410.1 142.8 187.0 411.2; qty:100 200 300 150 250)
topN[trade; 3] / top 3 by price
topN[trade; 0N] / top 5 (default)Explanation
$[null n; 5; n] is a three-part conditional: if n is null, return 5; otherwise return n as-is. This line always runs first so every subsequent line in the function can treat n as a guaranteed non-null value.
null returns 1b for any typed null: 0N (long null), 0n (float null), ` (symbol null), 0Np (timestamp null), and so on. This makes the pattern work regardless of what type the caller passes for the missing argument.
Alternative using fill (^):
topN:{[t; n]
n: 5 ^ n;
select[n; >price] from t
}5 ^ n replaces n with 5 if n is null. This is slightly shorter but less explicit — prefer $[null n; ...] when the logic is part of a longer function and you want it to read clearly.
Calling convention:
By convention, callers signal "use the default" by passing the appropriate typed null. For a long argument, that is 0N; for a float, 0n; for a symbol, `. Document this in the function's header comment so callers know what to pass.