This repository was archived by the owner on Sep 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathfunctional.mon
More file actions
90 lines (73 loc) · 1.67 KB
/
Copy pathfunctional.mon
File metadata and controls
90 lines (73 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// This script contains some functional programming examples.
//
// Launch this like so:
//
// ~$ monkey examples/functional.mon
//
//
// Return true if the given number is even
//
function even?(n) {
return( n % 2 == 0 );
}
//
// Return true if the given number is odd.
//
function odd?(n) {
return( n % 2 == 1 );
}
/*
* Return true if the given number is prime
*
* Remember we can use multi-line comments too!
*/
function prime?(n) {
// negative numbers are not prime
if ( n < 0 ) { return false ; }
// 0, 1, 2 are prime
if ( n < 3 ) { return true ; }
// Now the rest - we're testing all factors between 2 & SQRT(n).
let i = int(math.sqrt(n)) + 1;
for( i > 2 ) {
i--;
if (n % i == 0) {
return false;
}
}
return true;
}
//
// Square the given number.
//
function square(n) { return n * n ; }
//
// The list of numbers we'll operate upon.
//
let ints = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ];
// Show them ..
puts( "\nIntegers:\n" );
puts( "\t", ints, "\n" );
//
// Show their squares ..
//
puts( "\nSquares:\n" );
puts( "\t", ints.map(square), "\n");
//
// Show their cubes, using an anonymous function
//
puts( "\nCubes:\n" );
puts( "\t", ints.map( fn(n) { return n * n * n; }), "\n");
puts( "\nCubes via POW:\n" );
puts( "\t", ints.map( fn(n) { return n ** 3; }), "\n");
//
// Now use our functional-methods to show odd/even/prime
// numbers contained in our list.
//
puts( "\nOdd numbers:\n" );
puts( "\t", ints.filter(odd?), "\n");
puts( "\nEven numbers:\n" );
puts( "\t", ints.filter( even?), "\n");
puts( "\nPrime numbers:\n" );
puts( "\t", ints.filter( prime?), "\n");