News for hackers. Stuff that matters.
Re:Currying in JavaScript by neurotrace on Sunday September 19, 2021 @08:03AM (#28583663)
I've felt this same sort of pain but I don't blame currying. It's when currying and partial application is used for deep dependency injection with no easy route to finding the original function. I dabbled in writing an extension for F# that would trace back function calls to give you all of the possible original sources for a value. I think that would solve that particular problem.

Currying and partial application are really nice when you have a pipeline operator, which is why the partial application and pipeline operator proposals are so intertwined.

    users
    |> List.map (fn user -> user.Email)
    |> sendEmail
    |> Result.mapError (fn _ -> "Error sending emails")
Re:Currying in JavaScript by masklinn on Sunday September 19, 2021 @09:12AM (#28584069)
> Currying and partial application are really nice when you have a pipeline operator

Currying != partial application.

And while currying is useful in curried languages (to convert back from uncurried to curried), and partial application is useful period, the question is whether currying is useful, in general, in an uncurried language.

I don't think it is:

* You usually want to perform partial application, currying is an unnecessary intermediate step.

* Currying conflicts with rich "imperative" parameters e.g. overloading, default parameters, keyword parameters.

* Uncurried languages are usually imperative and effectful, that you have filled all the parameter spots does not mean you want to invoke the function.

Having a curried language is neat, and in curried languages converting back from uncurried to curried functions is tremendously useful. But it's not so for uncurried languages (which is most of them).

> which is why the partial application and pipeline operator proposals are so intertwined.

Again, partial application != currying. And pipeline operators can perform partial application (implicitly or explicitely) on their own. For a flagrant example, just see Clojure:

    (->> users
     (map :email)
     (sendEmail)
     (mapError (constantly "Error sending emails"))
Re:Currying in JavaScript by brundolf on Sunday September 19, 2021 @11:13AM (#28584944)
I'm not sure I fully appreciate the distinction you're trying to make here: "currying != partial application". Can you clarify?

In particular I don't know what's meant by "curried" and "uncurried" languages

Re:Currying in JavaScript by djur on Sunday September 19, 2021 @11:46AM (#28585254)
In Standard ML and Haskell, all functions are curried by default -- they take a single argument, and the syntax for defining multiple-argument functions is just sugar for defining single-argument functions that return single-argument functions. That's reflected in this Haskell type signature for a function adding two integers:

   add :: Int -> Int -> Int
This is a function that takes one integer and returns a function which itself takes another integer and then finally returns an integer. Syntax sugar allows you to define it and call it like a single function.

An uncurried function in these languages is a function that takes multiple arguments as a tuple.

   add :: (Int, Int) -> Int
You don't see a lot of functions defined this way in Haskell because there isn't really any advantage to doing so in a lazy, pure language. It's more common in Standard ML from what I've seen, because SML is strict and impure.
Re:Currying in JavaScript by masklinn on Sunday September 19, 2021 @11:43AM (#28585216)
> I'm not sure I fully appreciate the distinction you're trying to make here: "currying != partial application". Can you clarify?

Currying is the conversion of an n-ary function into a chain of 1-ary function e.g. `fn(a, b, c) -> d` becomes `fn(a) -> fn(b) -> fn(c) -> d`.

Partial application is what it says on the tin, it only applies k parameters to the function returning an (n-k) parameters function, without actually running the function.

Currying is one method allowing partial application, but not necessarily the only one, or usually the best fit as it tends to not interact well with features like overloading, default parameters, keyword parameters, …

> In particular I don't know what's meant by "curried" and "uncurried" languages

Languages like Haskell, OCaml, or Elm are "curried" by default: when you define an n-ary function it's really just sugar for a chain of 1-ary functions; and the application of multiple arguments is similarly the implicit application of single arguments multiple times e.g.

    map : (a -> b) -> List a -> List b
    map f l =
      case l of
        [] -> []
        (h::t) -> (f h) :: (map f t) 
can be called as

    map fn [1, 2, 3]
or

    (map fn) [1, 2, 3]
the semantics are identical, which is not the case in an uncurried language like Javascript or Python:

    map(fn, [1, 2, 3])
and

    map(fn)([1, 2, 3])
will behave very differently unless the implementer has taken special steps to handle this case e.g. dynamic behaviour based on an optional second parameter, overloading, etc…
Re:Currying in JavaScript by brundolf on Sunday September 19, 2021 @12:22PM (#28585543)
> applies k parameters to the function returning an (n-k) parameters function, without actually running the function

What would be the use of this? Just delaying the execution of the function's side-effects?

I'll tip my hand: I'm working on a JS-like (and JS-targeted) language that I want to support partial-application/currying by default. Under the hood everything is represented in a curried way, but syntactically you can both define and invoke/partially-invoke functions with the more familiar syntax (commas). But this is fully superficial right now; it all happens at the parser level. Is there a downside to doing things this way?

Re:Currying in JavaScript by djur on Sunday September 19, 2021 @02:51PM (#28586862)
The downside is that curried functions make default, optional, and keyword parameters difficult to implement.

For defaults/optionals, given "fn f(x, y, z=10)", if "f(1, 2)" evaluates to "f(1)(2)", does that return a function or the result of "f(1)(2)(10)"? What if you have "fn f(x, y = 10, z)"? All of this is a lot easier if you can evaluate the full argument list at the time of function invocation.

As for keyword arguments, they just don't play well with any kind of enforced ordering.

Re:Currying in JavaScript by brundolf on Sunday September 19, 2021 @03:18PM (#28587066)
Got it.

I wonder if that ambiguity could be resolved using contextual type info? I.e. if one of the two interpretations fits the expected type, use that. Otherwise, type-error.

Maybe that would be confusing, not sure.

Re:Currying in JavaScript by flyingchipmann on Sunday September 19, 2021 @12:59PM (#28585877)
If you come from typical oop background like java. Imagine there is a function has 5 parameters, and you need to to provide the first 3 first. Then later on you are using this partially applied function somewhere else. You can even reuse it later with different 2 params. Compare to class, it's just like how you initialize an object with certain values, then do something else with this object.
Re:Currying in JavaScript by RexM on Sunday September 19, 2021 @04:22PM (#28587583)
Bagel?

I read your post yesterday. Good luck with your language!

Re:Currying in JavaScript by brundolf on Sunday September 19, 2021 @04:56PM (#28587848)
Yes, thanks! :)

To be honest this comments section has me seriously reconsidering the "everything is partially-applicable by default" feature, haha.

Re:Currying in JavaScript by smohare on Sunday September 19, 2021 @12:00PM (#28585372)
At a deeper level currying is just a specific application of the Hom-tensor adjunction to the category of Sets. In particular the curried function is equivalent to the original. Partial function mappings is a restriction, and inherently not a injection. That is, generally the partial function is not in an equivalent Hom space to the original function.
Re:Currying in JavaScript by DemocracyFTW on Monday September 20, 2021 @04:52AM (#28591573)
そう言う事ですね〜ッ。は〜い
Re:Currying in JavaScript by creata on Sunday September 19, 2021 @02:49PM (#28586846)
> Currying conflicts with rich "imperative" parameters e.g. overloading, default parameters, keyword parameters.

This doesn't contradict anything you said, but I think Idris is a language that curries everything and has default parameters.

https://docs.idris-lang.org/en/latest/tutorial/miscellany.ht...

Re:Currying in JavaScript by BiteCode_dev on Sunday September 19, 2021 @10:05AM (#28584402)
Agreed, and I really with partial() was a builtin in Python, instead of having to fetch it from functools. partial() is useful regularly, and much more explicit/flexible than a lambda for this specific use case.
Re:Currying in JavaScript by okasaki on Sunday September 19, 2021 @08:21AM (#28583749)
I don't see why that's better than the good old for loop.

    errors = list()
    for user in users:
        if not sendEmail(user.email)
            errors.append("Error sending emails")
Re:Currying in JavaScript by p2t2p on Sunday September 19, 2021 @09:56AM (#28584337)
For me, the functional/pipeline/call chain style changes perception from "how" to "what".

Because I say "what" do to do without going into details of "how" I feel like I have spent less mental capacity reading this portion of code.

However, it does require your transformations to be simple and composable, shove a giant multi-line lambda in there it yes, the loop will be better.

Re:Currying in JavaScript by neurotrace on Sunday September 19, 2021 @08:37AM (#28583837)
The example I gave was contrived. I frequently find myself modeling much of my logic as a series of data transformations. The more I can model logic like this, the easier it is to test.

For what it's worth, your example doesn't map 1-to-1 to the intention of what I wrote. Doing it in a more imperative style, I'd have to write

    emails = list()
    for user in users:
        emails.push(user.email)
    res = sendEmail emails
    if res.IsError:
        Error("Error sending emails")
    else:
        res
(excuse my pseudo Python)
Re:Currying in JavaScript by BiteCode_dev on Sunday September 19, 2021 @10:01AM (#28584374)
Excuses accepted. Imperative Python would really look like:

    try:
        return sendEmail(user.email for user in users)
    except IsError:
        Error("Error sending emails") # if it does something
I agree FP pipelines are nice, but not everything needs it.
Re:Currying in JavaScript by HugoDaniel on Sunday September 19, 2021 @09:13AM (#28584077)
nice one, however shouldn't good old for loops be done in ALGOL instead?
Re:Currying in JavaScript by nestorD on Sunday September 19, 2021 @12:59PM (#28585870)
Yes! Like having both pattern matching and tagged union type in a language, it is the synergy of the features that makes them significantly powerful.
Re:Currying in JavaScript by p2t2p on Sunday September 19, 2021 @09:44AM (#28584270)
Oh, the lengths people go to avoid OOP. Java:

    users.stream()
        .map(User::getEmail)
        .map(Email::send)
        .map(res -> "Error sending email: " + res)
        .collect(toList())
Re:Currying in JavaScript by creata on Sunday September 19, 2021 @02:40PM (#28586765)
What's "object-oriented" about that code? I'm suspicious of vague labels like "OOP" and "FP", but even some of the Java docs call Java's streams "functional-style".

https://docs.oracle.com/javase/8/docs/api/java/util/stream/p...

Re:Currying in JavaScript by y4mi on Sunday September 19, 2021 @10:45AM (#28584724)
the only issue with java in this context is that you'll need to create a new class/transfer object between each function call that does things.

with elixir (the previous example) you'd likely use simple hashmaps or lists like {email: "mail"} or [:error, "reason for failure"].

That doesn't sound like its amazing, but actually is in practice, because the whole language is written with that in mind (pattern matching to effectively do function/method overloading depending on the value of each argument for example)

its very concise while still being very explicit. The same would be possible with java, but you'll need to create a lot of classes/interfaces/enums/boilerplate to facilitate it.

i'd still prefer java any time at a dayjob though, because boring and dumb is generally better if you need to write code that's gonna be in use for decades... and likely going to be changed by a lot of people with varying levels of experience.

Re:Currying in JavaScript by nestorD on Sunday September 19, 2021 @12:56PM (#28585843)
Side note to say that the previous example is actually F#, a static typed language contrary to Elixir (to be fair Elixir was heavily inspired by F# and they look similar when only looking at snippets).
Re:Currying in JavaScript by qsort on Sunday September 19, 2021 @11:00AM (#28584842)
> the only issue with java in this context is that you'll need to create a new class/transfer object between each function call that does things

No, in most cases you don't. The stream interface is mostly designed around simple Lists, Sets and Maps. It also interacts very well with the Collection framework (e.g. myHashmap.entrySet() yielding a set, etc.) which is part of the standard library.

You can extend streams with custom collectors, but rarely if ever you need to define intermediate data structures. You do need to define initial and terminal structures, but I'd argue that's good practice regardless.

Re:Currying in JavaScript by y4mi on Sunday September 19, 2021 @11:35AM (#28585136)
> No, in most cases you don't

that lets you pass the result from each function to the next without explicitly stating what form they have, yes.

You'll still be missing the conciseness/explicitness because the language isn't meant to be used like that and is missing necessary features in order to facilitate it such as pattern matching by the passed in values into function.

to make a simple example, you could theoretically write the following pseudo-code

  def sendEmail({email}) do
    // send email
  end
  def sendEmail({id}) do
    // get email address
    sendEmail({email})
  end
  sendEmail({id: 244})
or to make sure your code stops executing if an error occurs (positional return values this time)

    [:ok, msg] = sendEmail(lkajsdf)
Re:Currying in JavaScript by qsort on Sunday September 19, 2021 @11:55AM (#28585342)

    .collect(Collectors.groupingBy(...))
Re:Currying in JavaScript by y4mi on Sunday September 19, 2021 @12:06PM (#28585415)
that does something entirely different.

maybe actually learn to program sometimes, then you will figure out what it does.

Re:Currying in JavaScript by runarberg on Sunday September 19, 2021 @02:03PM (#28586465)
We were hoping for similar operators in JavaScript (pipeline `|>` and partial application `?`). However TC39 just decided earlier this month that we users of the language are not worthy of such powers. This was off course meet with a lot of resentment from many JavaScript developers, including my self.

https://github.com/tc39/proposal-pipeline-operator

Re:Currying in JavaScript by Zababa on Sunday September 19, 2021 @05:40PM (#28588198)
Considering what happened with the monadic promises, that was to be expected. I hope we'll at least have the immutable records and tuples so that the JS engine can implement them efficiently. This way JS will become an even better compilation target.
Re:Currying in JavaScript by z3t4 on Sunday September 19, 2021 @09:47AM (#28584283)
You usually want to send the e-mail in order, with a sleep in between to not overload the e-mail server, and stop at any error, so that you can fix the error and then continue from where the error was.

An error could be a malformed e-mail address, or a timeout from the e-mail server.

What you do not want is to send 10000 e-mail, then have an error like "Error sending emails", then re-run a few time, only to have some people receive 5 e-mail, and some people receive 0 e-mail.

Re:Currying in JavaScript by neurotrace on Sunday September 19, 2021 @10:10AM (#28584449)
I didn't think I had to make this clear but a lot of people seem to be getting stuck on the specifics of my example code. That example is doing nothing but showing a 5,000 foot view of what pipelines can do. Please don't take my dumb example that was written early in the morning as The One True Way of processing data, sending emails, or handling errors. It's a horrible example of that
Re:Currying in JavaScript by z3t4 on Sunday September 19, 2021 @12:43PM (#28585718)
Simplified examples always look neat. Any code/syntax will look simple if it doesn't have async, state and error handling.
Re:Currying in JavaScript by neurotrace on Sunday September 19, 2021 @02:06PM (#28586485)
I can't be bothered to type all of it out on my phone but even adding in those pieces, it doesn't change it much. This is F# so you can easily manage the async via an async computation expression, the retry logic can be encapsulated in the `sendEmails` function, and the error handling is reduced to a `Result` which is very easy to work with in a pipeline. Not everything should be done in a pipeline but pipelines make a lot of things a lot nicer