Given the following code:
const K = a => b => a
const cat = 'cat'
const dog = 'dog'
Calling K like this will output cat
K(cat)(dog)
//=> "cat"
How can you call K to output dog without swapping the order of cat and dog?
cat and dog must appear exactly once.
The Given cannot be modified.
// INVALID: Cannot swap order!
K(dog)(cat)
// NO CHEATING: May only appear once.
K.bind(null, dog)(cat)(dog)
I know of two ways to solve this problem. Surprise me with another!
I should have also specified no bind, call, or apply, but the solutions are just too interesting :)
Hints: K in the problem is the K combinator, part of the SKI combinator calculus.
Spoilers are in the comments! BEWARE!
Many great solutions have been posted below! A lot I never considered. Also some very creative loopholes around the rules I created ;)
Here's one solution that went undiscovered. It's base64 encoded to hide the "spoiler". But if you are curious you can decode it using your console's atob function.
Syh4PT54KShjYXQpKGRvZyk=

Latest comments (40)
Well, I looked up SKI combinators. If I am understanding it correctly, and if I've implemented S correctly here...I think the following would work:
I am going to have to add "Learn SKI Combinators" to my list of things to do. :D
After you research SKI Combinators, look into Church Encoding.
Hey Joel, I enjoy your articles and I think you deliver a good contribution overall to this website but I would like to see you use better use cases in your examples than cats and dogs meowing. Not for me but for others less experienced. :)
But cats and dogs are the best ;)
Exactly! That is definitely the
Icombinator. It works beautifuly with theKcombinator in the problem to solve this problem.Two parts of
SKIcombinator calculus!This one is pretty creative. Modifying the original
Kfunction to swapaandb. I like it.I didn't see this one in the comments
And arrays are fun
Technically i think this follows the rules.
And if the does then this should work too
Beautiful!
Well...
Generators and iterators. quite a unique solution. I love it!
So many unique solutions. Fantastic!
?
Technically within the rules and as valid as any other solution!
Brilliant.
Do you really need the second
dogsince you already.bind?Maybe I do not understand, what is the second
dog?Comma operator:
Extra hearts for the comma operator. Kudos!