Skip to content

Instantly share code, notes, and snippets.

@fxg42
Last active November 7, 2015 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fxg42/80cf8af0595c93ec3e9b to your computer and use it in GitHub Desktop.
Save fxg42/80cf8af0595c93ec3e9b to your computer and use it in GitHub Desktop.
Exercices
// # Exercice 1:
// Étant données les deux fonctions suivantes:
// f :: a -> [b]
var f = (a) => [ a * a ];
// g :: a -> [b]
var g = (a) => [ a + 10 ];
// Écris l'implémentation de la fonction `compose` définie ainsi:
// compose :: (a->[b]) -> (b->[c]) -> (a->[c])
// p.e.
// var h = compose(f, g);
// h //=> (a) => [ (a+10) * (a+10) ]
// h(2) //=> [ 144 ]
var compose = (k1, k2) => {
// ???
};
// # Exercice 2:
// Étant données `f`, `g` et `compose`, écris la fonction `bind` définie ainsi:
// bind :: [a] -> (a -> [b]) -> [b]
// p.e.
// bind([1,2,3], compose(f,g)) //=> [121, 144, 169]
var bind = (list, k) => {
// ???
};
// # Exercice 3:
// Vérifie que ceci est vrai:
//
// bind(bind([1,2,3], g), f) === [121, 144, 169]
// # Exercice 1:
// Étant données les deux fonctions suivantes:
// f :: a -> [b]
var f = (a) => [ a * a ];
// g :: a -> [b]
var g = (a) => [ a + 10 ];
// Écris l'implémentation de la fonction `compose` définie ainsi:
// compose :: (a->[b]) -> (b->[c]) -> (a->[c])
// p.e.
// var h = compose(f, g)
// h === (a) => [ (a+10) * (a+10) ]
// h(2) == [ 144 ]
// fmap :: [a] -> (a -> b) -> [b]
var fmap = (xs, f) => {
return xs.reduce((acc, x) => acc.concat(f(x)), []);
};
// join :: [[a]] -> [a]
var join = (xss) => {
return xss.reduce((acc, xs) => acc.concat(xs), []);
};
// compose :: (a->[b]) -> (b->[c]) -> (a->[c])
var compose = (k1, k2) => {
return (a) => join(fmap(k2(a), k1));
};
console.log( compose(f,g)(2) );
// # Exercice 2:
// Étant données `f`, `g` et `compose`, écris la fonction `bind` définie ainsi:
// bind :: [a] -> (a -> [b]) -> [b]
// bind([1,2,3], compose(f,g)) === [121, 144, 169]
// Vérifie que ceci est vrai:
// bind(bind([1,2,3], g), f) === [121, 144, 169]
// bind :: [a] -> (a -> [b]) -> [b]
var bind = (xs, k) => {
return join(fmap(xs, k));
};
console.log( bind([1,2,3], compose(f, g)) );
console.log( bind(bind([1,2,3], g), f) );
// # Exercice 3:
// ap :: [a] -> [a -> b] -> [b]
var ap = (xs, fs) => {
return join(fmap(fs, (f) => fmap(xs, f)));
};
var fp = (a) => a * a;
var gp = (a) => a + 10;
console.log( ap([1,2,3], [fp, gp]) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment