Learn › Beginner · Lesson 10 of 11

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

Open in playground

How to read it:

A function may use another function. Functions that call themselves (recursion) are an Advanced topic.

Try it in the playground

  1. The answer is there as the program opens, with no button to press: moving3[t = 2] is 22.
  2. Query wave and distance and look at their pictures in Visualize.
  3. Change the 0.5 in smoothed to 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.