Subprograms
Functions

 Subprograms are Mint's version of what are called 'functions' in other programming languages. To define a subprogram, use the keyword sub, followed by the name of the subprogram, and then a comma-separated list of parameters surrounded by parentheses. ```sub square(x) return x ^ 2 end sub max(x, y) when x > y return x return y end print max(60, square(30)) //Prints 900.``` Subprograms return values using the return statement. Notice that in the above code, we defined x inside one subprogram and also in another. These two subprograms do not get confused about the value of x because each keeps their own separate x variable. The local variables of a subprogram only exist in that subprogram. To write a single line function in Mint, use the function keyword. ```// In Mint, a function's yields // statement is the same as a subprogram's // return statement. // Mint's yields is not equivalent to Python's yield. function f of x yields x*x function twice of y yields 2(y) function fOfTwice of k yields f(twice(k)) tenSquared = f(10) eightDoubled = twice(8) import math goldenRatioDoubledThenSquared = fOfTwice(phi) print tenSquared print eightDoubled print goldenRatioDoubledThenSquared``` Subprograms can define other subprograms within themselves, and even return them. Here is a subprogram that squares a subprogram: ```sub squareSub(f) sub squared(x) return f(x) ^ 2 end return squared end sub quadratic(x) return 3 * x ^ 2 + 6 * x - 15 end g = squareSub(quadratic) print g(9)``` Subprograms support closures, which means they can enclose data and even form their own data structures. ```sub tripleList(a, b, c) sub get(i) if i == 0 return a else if i == 1 return b else return c end end return get end x = tripleList(6, 7, 81) print x(0) //Prints 6 print x(2) //Prints 81``` Finally, subprograms support recursion. You have the ability to call a subprogram within itself. ```sub factorial(x) when x <= 1 return 1 return x * factorial(x - 1) end sub fib(n) when n <= 1 return n return fib(n - 1) + fib(n - 2) end print factorial(8) print fib(11)``` You can make infinitely large lists by creating a list out of a subprogram. ```sub g(x) import math x = BigInt(x) return factorial(x) end import type y = list(g) //y represents the factorial of all integers print y //Prints [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, ...] print y /* Prints a very large number. */``` In this example we used the BigInteger type to represent factorials of large numbers. Creating a list out of a subprogram f will define list[x] as f(x) for all x that f is defined. Navigation Previous Lesson: Data Structures Next Lesson: Objects Table of Contents