prelude-ls
prelude-ls copied to clipboard
K Combinator
Would like to have the K combinator, or the function known as const
in Haskell, in prelude.ls. Since const
is already a keyword in LiveScript, I would suggest simply using k
or something else for its name.
The implementation should be straight forward in LiveScript: k = (x, y) --> x
or k = (x) -> (y) -> x
for better performance.
Can you give some use cases?
Prelude.ls is optimised for LiveScript, which has a terse lambda syntax. Just use -> value
. If the value is this
, use ~> this
. If the value is arguments
, you'll unfortunately have to use arguments |> (a) -> -> a
, but I think that's acceptable.
k
combinator is usually used when you don't need the full power that a higher-order function provides. One use case I encountered was that I had to reset a histogram to zero while preserving keys, the solution with map
and k
is: {a: 1, b: 2, c: 3} |> map (k 0) #=> {a: 0, b: 0, c: 0}
which is a lot more elegant than other ones I could think of (It reuses the part that Obj.map
preserve keys while ignoring its ability to transform original values). This also happens when you need to workaround some API's that takes a function when you only want to supply a constant value (hence the name const
).
I have thought about -> x
as well. They both should work equally well except that k
can be used point-free if needed. I think it is more of a style thing since I'm used to write const x
rather than \_ -> x
in Haskell, so naturally I was looking for one in LiveScript and that's why I opened this. Actually your comment made me realize that k = (x) -> -> x
should work as well.