// FizzBuzz program written in a purely functional way, first in Javascript and then in Haskell.
/* Limitations in Javascript when implementing pure functional programming :
No loops
No ifs
Function is a single return (its body is empty)
No side-effects (no interactions with the user)
No assignments in functions
No arrays ??
Only functions with 0 or 1 arguments
*/
/********************** Example of a pure function ---> use recursion instead of ifs *******************/
function sum(i) {
return i <= 0 ? 0: i + sum(i -1);
}
console.log('Suma: ' + sum(5))
/****************** After the video "Haskell for JavaScript programmers" ******************/
////////////////////////////// https://www.youtube.com/watch?v=pUN3algpvMs
let pair = (first) => (second) => {
return {
first: first,
second: second
};
};
let fst = (p) => p.first
let snd = (p) => p.second
console.log(snd (pair (10) (20)))
let xs = pair (3) (pair (2) (pair (1) (null)))
let head = fst // It's an alias
let tail = snd // It's an alias
// console.log(xs)
// console.log(head(xs))
// console.log(tail(xs))
/*
Non-pure function, bridge between the functional and the imperative worlds.
It takes a functional list.
*/
function list2array(xs) {
let result = [];
while (xs != null) {
result.push(head(xs));
xs = tail(xs);
}
return result;
}
/*************************************************************************/
let range = (low) => (high) =>
low > high
? null
: pair (low) (range (low + 1) (high))
let sequence = list2array(range (1) (100))
// console.log(sequence);
let map = (f) => (xs) =>
xs === null
? null
: pair (f (head (xs))) (map (f) (tail (xs)));
let fizzbuzz = (n) =>
((n % 3 === 0 ? 'fizz' : '') + (n % 5 === 0 ? 'buzz' : '') || n)
// console.log(list2array( map (fizzbuzz) (range (1) (100))) )
/*******************************************************************/
/************************ In Haskell *******************************/
/*******************************************************************/
/*
fizzbuzz n
| n `mod` 15 == 0 = "FizzBuzz"
| n `mod` 3 == 0 = "Fizz"
| n `mod` 5 == 0 = "Buzz"
| otherwise = show n
map fizzbuzz [1 .. 100]
*/