7 kyu

Chain me

4,483 of 7,370nrgarg

Description:

Write a generic function chainer

Write a generic function chainer that takes a starting value, and an array of functions to execute on it (array of symbols for Ruby).

The input for each function is the output of the previous function (except the first function, which takes the starting value as its input). Return the final value after execution is complete.

function add(num) {
  return num + 1;
}

function mult(num) {
  return num * 30;
}

chain(2, [add, mult]);
// returns 90;
add = (+ 1)
mul = (* 30)

chain 2 [add, mult] -> 90
def add num
  num + 1
end

def mult num
  num * 30 
end

chain(2, [:add, :mult])
#=> returns 90
double input = 2;

public static double add(double x) {
  return x + 1;
}

public static double mul(double x) {
   return x * 30;
}
Kata.Chain( input , new[] { (Func<double, double>)add, mul });
//=> returns 90
int add10 (int x) { return x + 10; }
int mul30 (int x) { return x * 30; }

typedef int (*funcptr) (int);

chain(50, 2, (funcptr[2]) {add10, mul30});
// returns 1800
def add10(x): return x + 10
def mul30(x): return x * 30

chain(50, [add10, mul30])
# returns 1800
: add10 ( x -- r ) 10 + ;
: mul30 ( x -- r ) 30 * ;

50 { [ add10 ] [ mul30 ] } chain
! returns 1800
let add n = n + 1 in
let mult n = n * 30 in

chain 2 [add; mult] (* -> 90 *)
add(X,R):-R is X+1.
mul(X,R):-R is X*30.

?- chain(2,[add,mul],Result). % Result = 90.
fn add10(x) { x + 10 }
fn mul30(x) { x + 30 }

chain(50, &[&add10, &mul30]) //=> returns 1800
Fundamentals

More By Author:

Check out these other kata created by nrgarg

Stats:

CreatedMar 7, 2015
PublishedMar 7, 2015
Warriors Trained15277
Total Skips1091
Total Code Submissions23269
Total Times Completed7370
JavaScript Completions4483
Ruby Completions654
C# Completions603
C Completions167
Haskell Completions93
Julia Completions23
Python Completions1481
Factor Completions14
OCaml Completions71
NASM Completions19
Prolog Completions13
Rust Completions113
Total Stars128
% of votes with a positive feedback rating92% of 782
Total "Very Satisfied" Votes681
Total "Somewhat Satisfied" Votes79
Total "Not Satisfied" Votes22
Ad
Contributors
  • nrgarg Avatar
  • jhoffner Avatar
  • dramforever Avatar
  • aryan-firouzian Avatar
  • JohanWiltink Avatar
  • B1ts Avatar
  • nomennescio Avatar
  • monadius Avatar
  • Awesome A.D. Avatar
  • hobovsky Avatar
  • stellartux Avatar
  • albertogcmr Avatar
  • trashy_incel Avatar
  • akar-0 Avatar
  • Kacarott Avatar
  • ksaweryr Avatar
  • Glinator Avatar
  • razetime Avatar
Ad