Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical use of K-combinator (Kestrel) in javascript

The K-combinator can be implemented as below and the implementation should not have any side-effects.

const K = x => y => x;

It is sometimes called "const" (as in Haskell). The K function might be defined as, "takes a value and returns a (constant) unary function that always returns that value."

When is it useful? Please help me with practical examples.

like image 474
Jyoti Prasad Pal Avatar asked Jul 28 '16 11:07

Jyoti Prasad Pal


People also ask

What is a combinator functional programming?

A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments.

What is K combinator?

The K-combinator can be implemented as below and the implementation should not have any side-effects. const K = x => y => x; It is sometimes called "const" (as in Haskell). The K function might be defined as, "takes a value and returns a (constant) unary function that always returns that value."


1 Answers

Sort of an broad question, but it's nice, I like it.

To support my example, in this answer I'm going to implement …

abuild :: Number -> (Number -> a) -> [a]

… which as the type suggests, takes a number and a function to build an array. This could be useful if you want to build an array of a known size based on some computation.


Let's build an array with 5 elements using the identity function, id. As you can see, a sequential numerical index starting with 0 is given to your builder function

abuild (5) (id) // => [0,1,2,3,4]

Let's do something mathy with the builder this time. We'll square the input. Very advanced.

abuild (5) (x=> x * x)
// => [0,1,4,9,16]

Or maybe we don't care about the input. I always love a good laugh. I laugh at things constantly. One could say I K('ha')

abuild (5) (K('ha'))
// => ['ha','ha','ha','ha','ha']

Boom ! Pretty useful, right? That's K


Implementation

Go ahead and run it to see K in action!

// id :: a -> a
const id = x=> x

// K :: a -> b -> a
const K = x=> y=> x

// add :: Number -> Number -> Number
const add = x=> y=> y + x

// reduce :: (a -> b) -> b -> [a] -> b 
const reduce = f=> y=> ([x,...xs])=> {
  if (x === undefined)
    return y
  else
    return reduce (f) (f (y) (x)) (xs)
}

// map :: (a -> b) -> [a] -> [b]
const map = f=> reduce (xs=> x=> [...xs, f(x)]) ([])

// iterate :: Number -> (a -> a) -> a -> [a]
const iterate = n=> f=> x=>
  n > 0 ? [x, ...iterate (n - 1) (f) (f(x))] : []

// abuild :: Number -> (Number -> a) -> [a]
const abuild = n=> f=>
  map (f) (iterate (n) (add (1)) (0))

console.log(abuild (5) (id))
// => [0,1,2,3,4]

console.log(abuild (5) (x=> x * x))
// => [0,1,4,9,16]

console.log(abuild (5) (K('ha')))
// => ['ha','ha','ha','ha','ha']
like image 191
Mulan Avatar answered Sep 23 '22 15:09

Mulan