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.
A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments.
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."
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With