Learning Functions in JSL¶
Introduction¶
Functions are the building blocks of JSL programs. In this tutorial, you'll learn to create, use, and combine functions through hands-on examples.
Your First Function¶
Let's start with the simplest possible function:
This is the identity function - it returns whatever you give it. Try it:
Naming Functions¶
Usually, you'll want to give functions names:
Now you can use it by name:
Functions with Multiple Parameters¶
Step-by-Step: Building a Math Library¶
Step 1: Basic Operations¶
["do",
["def", "square", ["lambda", ["x"], ["*", "x", "x"]]],
["def", "double", ["lambda", ["x"], ["*", "x", 2]]],
["def", "half", ["lambda", ["x"], ["/", "x", 2]]]]
Step 2: Test Your Functions¶
Step 3: Combining Functions¶
["def", "square_and_double",
["lambda", ["x"], ["double", ["square", "x"]]]]
["square_and_double", 3]
// 3 → square → 9 → double → 18
Higher-Order Functions¶
Functions that work with other functions:
Step 1: A Function That Applies Another Function Twice¶
Step 2: Use It¶
Working with Lists¶
Step 1: Processing Each Item¶
Step 2: Filtering Lists¶
["def", "is_even", ["lambda", ["x"], ["=", ["mod", "x", 2], 0]]]
["filter", "is_even", "numbers"]
// Result: [2, 4]
Step 3: Combining Operations¶
["def", "sum_of_squares_of_evens",
["lambda", ["numbers"],
["sum", ["map", "square", ["filter", "is_even", "numbers"]]]]]
["sum_of_squares_of_evens", [1, 2, 3, 4, 5]]
// [1,2,3,4,5] → filter evens → [2,4] → square → [4,16] → sum → 20
Closures: Functions That Remember¶
["def", "make_adder",
["lambda", ["n"],
["lambda", ["x"], ["+", "x", "n"]]]]
["def", "add_10", ["make_adder", 10]]
["add_10", 5]
// Result: 15
The inner function "remembers" the value of n (10) even after make_adder finishes.
Practice Exercises¶
Exercise 1: Temperature Converter¶
Create functions to convert between Celsius and Fahrenheit:
// Your solution here
["def", "celsius_to_fahrenheit", ["lambda", ["c"], ...]]
["def", "fahrenheit_to_celsius", ["lambda", ["f"], ...]]
Solution
Exercise 2: List Statistics¶
Create a function that returns statistics about a list of numbers:
Solution
Next Steps¶
- Learn about working with data
- Explore JSON Objects as first-class citizens
- Try distributed computing
Functions in JSL are powerful and flexible. With closures and higher-order functions, you can build complex programs from simple, composable pieces.