Programming-Idioms

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

Idiom #35 First-class function : compose

Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns composition function g ∘ f

(defn compose [f g]
   (comp g f))
#include <functional>
std::function<C (A)> compose(B (&f)(A), C (&g)(B))
{
    return [&f, &g](A a){return g(f(a));};
}

auto fn = compose(f, g);
Func<A, C> compose<A, B, C>(Func<A, B> g, Func<B, C> f) => (A a) => f(g(a));
import std.functional;
auto compose(f, g) {
	return std.functional.compose!(f, g);
}
typedef R Func<T,R>(T arg);

Func<A,C> compose(B f(A x), C g(B x)) => (A x) => g(f(x))
def compose(f, g) do
  fn a ->
    g.(f.(a))
  end
end
-spec compose(fun((A) -> B), fun((B) -> C)) -> fun((A) -> C).
compose(F, G) -> fun(X) -> G(F(X)) end.
func compose(f func(A) B, g func(B) C) func(A) C {
	return func(x A) C {
		return g(f(x))
	}
}
compose :: (A -> B) -> (B -> C) -> A -> C
compose = flip (.)
compose :: (A -> B) -> (B -> C) -> A -> C
compose f g x = g (f x)
function compose(f,g){
    return function(x){
        return g(f(x));
    };
}
import java.util.function.Function;
Function<Integer, Integer> addOne = i-> i + 1;
Function<Integer, String> toString = i-> i.toString();
Function<Integer, String> printIncremented = toString.compose(addOne);
public <A,B,C> Function<A,C> compose(Function<A,B> f, Function<B,C> g){
   return x -> g.apply(f.apply(x));
}
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 {
      return $g->($f->(shift))
   }
}

sub double { return 2*shift }
sub triple { return 3*shift }
sub aFunc = compose(\&double, \&triple);
aFunc->(7);
def compose(f, g):
    return lambda a: g(f(a))
def compose(f, g)
  -> x { g.(f.(x)) }
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) (g (f (x)))))

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

Idiom created by

programming-idioms.org

Related idioms