6.5 One-Line Functions

As you use FriCAS, you will find that you will write many short functions function:one-line definition to codify sequences of operations that you often perform. In this section we write some simple one-line functions.

This is a simple recursive factorial function for positive integers.

fac n == if n < 3 then n else n * fac(n-1)

Type: Void

fac 10
\[\]
3628800

Type: PositiveInteger

This function computes 1+1/2+1/3+...+1/n.

s n == reduce(+,[1/i for i in 1..n])

Type: Void

s 50
\[\]
139432375772240549607593099044504245996706400

Type: Fraction Integer

This function computes a Mersenne number, several of which are prime. Mersenne number

mersenne i == 2^i - 1

Type: Void

If you type mersenne, FriCAS shows you the function definition.

mersenne
\[\]
mersennei==2i-1

Type: FunctionCalled mersenne

Generate a stream of Mersenne numbers.

[mersenne i for i in 1..]
\[\]
[1,3,7,15,31,63,127,255,511,1023,…]

Type: Stream Integer

Create a stream of those values of i such that mersenne(i) is prime.

mersenneIndex := [n for n in 1.. | prime?(mersenne(n))]
Compiling function mersenne with type PositiveInteger -> Integer
\[\]
[2,3,5,7,13,17,19,31,61,89,…]

Type: Stream PositiveInteger

Finally, write a function that returns the n-th Mersenne prime.

mersennePrime n == mersenne mersenneIndex(n)

Type: Void

mersennePrime 5
\[\]
8191

Type: PositiveInteger