Functions in Wolfram Language

Functions are central in Wolfram Language. We’ll learn about functions with a few different examples.

(* Here's a function that takes two integers and returns their sum *)
plus[a_, b_] := a + b

(* Wolfram Language doesn't require explicit returns. The last expression 
   in a function is automatically returned *)

(* Here's a function that takes three parameters and returns their sum *)
plusPlus[a_, b_, c_] := a + b + c

(* In the main part of our program *)
res = plus[1, 2]
Print["1+2 = ", res]

res = plusPlus[1, 2, 3]
Print["1+2+3 = ", res]

To run this code, you can save it in a file (e.g., functions.wl) and evaluate it in a Wolfram Language kernel or notebook.

(* Output *)
1+2 = 3
1+2+3 = 6

Let’s break down some key differences and features:

  1. Function Definition: In Wolfram Language, we define functions using the := operator. The square brackets [] are used for function arguments.

  2. Naming Conventions: Wolfram Language typically uses camelCase for function names, but we’ve kept the names consistent with the original example.

  3. Argument Types: Wolfram Language is dynamically typed, so we don’t need to specify types for function arguments.

  4. Return Values: Wolfram Language automatically returns the last expression in a function, so we don’t need an explicit return statement.

  5. Main Function: There’s no explicit main function in Wolfram Language. We simply write the code we want to execute at the top level.

  6. Printing: We use the Print function to output results, which is similar to fmt.Println in the original example.

Wolfram Language offers powerful functional programming capabilities, and there are often multiple ways to achieve the same result. This translation aims to stay close to the original structure while introducing idiomatic Wolfram Language concepts.

There are several other features to Wolfram Language functions, including pattern matching and pure functions, which we’ll explore in future examples.