Learn K with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
K Counter and Theme Toggle
count:0
isDark:0
updateUI:{
'Counter: ', string count
'Theme: ', (if[isDark; 'Dark'; 'Light'])
}
increment:{
count+:1
updateUI[]
}
decrement:{
count-:1
updateUI[]
}
reset:{
count:0
updateUI[]
}
toggleTheme:{
isDark:1-isDark
updateUI[]
}
/ Simulate actions
updateUI[]
increment[]
increment[]
toggleTheme[]
decrement[]
reset[]
Demonstrates a simple counter with theme toggling using K variables and functional style.
2
K Fibonacci Sequence
fib:0 1
10{fib,:{x,y:x+y} last 2 fib}
Generates first 10 Fibonacci numbers using K arrays.
3
K Factorial Calculator
fact:{[n] $[n=0;1;n*fact[n-1]]}
fact[5]
Calculates factorial of a number using K's functional style.
4
K Prime Checker
isPrime:{[n] n>1 & all n mod 2_til n-1}
isPrime[13]
Checks if a number is prime using modulo and all.
9
K Simple Alarm Simulation
temp:80
thresh:75
$[temp>thresh;'Alarm: Temp Too High!';'Temp Normal']
Simulates an alarm if threshold exceeded.
10
K Random Walk Simulation
steps:10
pos:0
10{pos+:2?2-1; pos}
Simulates a 1D random walk.