Logo

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)); };	
}
using System;
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 compose[T, U, V any](f func(T) U, g func(U) V) func(T) V {
	return func(x T) V {
		return g(f(x))
	}
}
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
function compose(f,g){
    return function(x){
        return g(f(x));
    };
}
const compose = f => g => x => 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));
    }
(defun compose (f g)
  (lambda (x) (g (f 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 {
      my $x = shift;
      return $g->($f->($x));
   }
}
def compose(f, g):
	return lambda x: g(f(x))
compose = lambda f, g, x: g(f(x))
def compose(f, g)
  f >> g
end
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 
		(f (apply g x))))
(define compose
 (lambda (f g)
   (lambda (x) (f (g x)))))
Imports System
Function Compose(Of T1, T2, T3)(f As Func(Of T1, T2), g As Func(Of T2, T3)) As Func(Of T1, T3)
    Return Function(x) g(f(x))
End Function

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