Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #36 First-class function : generic composition

Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.

(comp g f)
template<typename Pred1, typename Pred2>
auto compose(Pred1 f, Pred2 g){
  return [f,g](auto x){ return g(f(x)); };	
}
Func<T1, T3> Compose<T1, T2, T3>(Func<T1, T2> f, Func<T2, T3> g) => x => g(f(x));
auto _compose(T)(T function(T) f, T function(T) g)
{
    auto lambda = (T x) { return g(f(x));  };
    return lambda;
}
compose(f, g) => (x) => g(f(x));
-spec compose(fun((X) -> Y), fun((Y) -> Z)) -> fun((X) -> Z).
compose(F, G) -> fun(X) -> G(F(X)) end.
func composeIntFuncs(f func(int) int, g func(int) int) func(int) int {
	return func(x int) int {
		return g(f(x))
	}
}
compose f g = g . f
const compose = f => g => x => g(f(x));
function compose(f,g){
    return function(x){
        return g(f(x));
    };
}
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
function compose(f,g)
   return function(x)
      return g(f(x))
   end
end
function compose($f,$g){
	return function($x) use($f,$g) {
		return $g($f($x));
	}
}
sub compose {
   my ($f, $g) = @_;
   return sub {
      my $x = shift;
      return $g->($f->($x));
   }
}
def compose(f, g):
	return lambda x: g(f(x))
def compose(f, g)
  -> x { g.(f.(x)) }
end
def compose(f, g)
  f >> g
end
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |x| g(f(x))
}
fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
	where F: 'a + Fn(A) -> B, G: 'a + Fn(B) -> C
{
	Box::new(move |x| g(f(x)))
}
(define (compose f g) 
	(lambda x 
		(f (apply g x))))

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms