Logo

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 the composition function g ∘ f

function compose(f,g)
   return function(x)
      return g(f(x))
   end
end
(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);
using System;
Func<A, C> compose(Func<A, B> f, Func<B, C> g) => a => g(f(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));
    };
}
public Function<A, C> compose(Function<A, B> f, Function<B, C> g) {
   return x -> g.apply(f.apply(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);
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, 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)))
}
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |x| g(f(x))
}
(define (compose f g)
  (lambda (x) (g (f (x)))))
Imports System
Function compose(f As Func(Of A, B), g As Func(Of B, C)) As Func(Of A, C)
    Return Function(a) g(f(a))
End Function

New implementation...
< >
programming-idioms.org