#Functions, where, and maths
A function names a piece of a program to use again. It applies to whole values over their dimensions, not to single numbers: prev(reading) is the whole row of readings, one step back. where gives a function, or a value, local values of its own. And eLucid8 has the usual maths functions.
-- Your own functions, and maths functions.
reading = restrict 20 + mod(#t * 7, 5) to (t : 10) end
fun prev(v) = v fby.t v
fun smooth(v, a) = s
where
s = v fby.t a * next.t v + (1 - a) * s
end
moving3 = (reading + prev(reading) + prev(prev(reading))) / 3
smoothed = smooth(reading, 0.5)
wave = restrict sinpi(#t / 10) to (t : 40) end
distance = restrict sqrt(#x * #x + #y * #y) to (x : 10, y : 10) end
-- ask moving3[t = 2]
-- expect moving3[t = 2] = 22
-- expect smoothed[t = 1] = 21
-- expect wave[t = 5] = 1
-- expect distance[x = 3, y = 4] = 5
How to read it:
fun prev(v) = v fby.t visvone step back (andvitself at the first step).moving3averages a reading with the two before it: att = 2, (24 + 22 + 20) / 3 = 22.smooth(v, a)smooths a value: each step movessa fractionaof the way towards the next reading.sis local to the function, written afterwhereand closed byend. Witha = 0.5: 20, then halfway to 22, which is 21.sinpi(z)is the sine of π timesz, andsqrtthe square root:waveis a sine wave with a period of 20 steps, anddistanceeach point's distance from the corner, 5 atx = 3, y = 4. Others:sin,cos,exp,log,abs,minandmaxof two numbers,floor,round,mod, and the constantspiande. The Quick reference lists them all.
A function may use another function. Functions that call themselves (recursion) are an Advanced topic.
#Try it in the playground
- The answer is there as the program opens, with no button to press:
moving3[t = 2] is 22. - Query
waveanddistanceand look at their pictures in Visualize. - Change the 0.5 in
smoothedto 0.1: the row redraws by itself, smoother and slower to follow the readings.
#Ask your own AI
Using eLucid8's reference at https://elucid8-lang.org/llms.txt, write a Beginner eLucid8 program (equations only: no input or output lines) with a function that gives the largest of the last three values of a row, used on ten made-up readings. Compile it with the elucid8 tools before you show it, and give me its Open in playground link.