75 points · by peter_d_sherman · 2y ago · 128 comments
splitString :: { pattern :: String, string :: String } -> Array String
splitString { pattern, string } = ...
This function would use positional arguments: splitString :: Pattern -> String -> Array String
splitString pattern string = ...Number.parseInt('10', 0) Number.parseInt('10', 1) Number.parseInt('10', 2)
JavaScript lacks typing, and then they decided on a weird signature for the callback...
It's a very nasty issue to debug.
Method calls are easier to read and work better with autocomplete.
In addition to that, I don't always find the constructor/method approach more readable. It _can_ be readable, if you design your API with care; however, it is common to group related data into records in the FP world as well, which mimicks OOP constructors, in a sense.
If currying isn’t built-in, you can emulate it. In TypeScript you need to do it explicitly, which means anticipating that it will be used, and whenever I try that, I later decide that it’s needlessly obscure and rewrite the code some other way.
Even with built-in currying, you still need to anticipate usage by changing the order of the parameters, based on which ones you expect the callers to have first. It’s less general than writing an inline function with exactly the parameters you need. TypeScript has nice syntax for defining tiny, one-off functions and I think that’s better than having currying.
One side-effect of having currying in a language is that it discourages naming things, and I think that’s often bad for readability. A chain of method calls gives you a lot of names to look up and a place to put documentation.
What currying in Haskell and any other ML does, is the following as Javascript. Let's say we have a function with four parameters `func(a, b, c, d) {return a + b + c + d;}`, then the curried version is the following:
func = (a) => {
return (b) => {
return (c) => {
return (d) => a + b + c + d;
}
}
}Instead of assuming you know better and jumping in with a correction, could you reread that post and assume that the person knows what they're talking about but isn't communicating exactly the way you would have communicated it? I.e., read with the intent of understanding intent, rather than read with the intent of correcting?
Though if enough people share the confusion, I guess it becomes an alternative definition. Language evolves.
Also, in any case, a constructed object is nothing like a partially applied function, so the parallel drawn is not useful. It seems entirely reasonable in this case to assume that the poster does not have sufficient experience or knowledge.
My answers are almost always less intented for the person who's post I'm responding to, but more for a general audience. As others have already posted the part about "currying isn't partial application", and I mainly wanted to add a (hopefully) understanable example.
And I would say that taking the OP's post as if he doesn't exactly know, what currying means in comparison to partia application _is_ the more favourable interpretation of their post.
Currying is a subset of partial application, so I suspect the person you're responding to is just being a bit loose with their wording, as opposed to not understanding the topic.
Some languages provide partial application without currying a function - JavaScript has bind, Python has functools.partial etc.
No, it isn't; it's a different operation.
Currying refers to building (effectively) functions of multiple arguments out of only one argument functions (such as in a language that has only those).
A curried function is not understood to have been applied, partially or otherwise; none of its arguments have been bound to values, thereby reducing its arity.
Partial application is an operation that requires one or more arguments. Currying does not require arguments; rather, the result of currying requires arguments (all of them).
There is a sort of partial application (effectively) going on when the curried function is applied to the arguments, which has to be done one argument at a time through the chain. At each step, one more argument is bound, and fewer remain.
However, I agree with the wording of the original comment: when you _pass_ some arguments to a constructor and then to a method, this is (at least conceptually) partial application.
It makes the code way less readable:
* more difficult to distinguish arguments and return values (there's a reason most languages have distinct syntax for them)
* it encourages you to put your arguments in an order that might not be the most logical
And on top of that it only works for the last argument(s).
Feels like a lot of disadvantages to allow an overly clever trick that you can do in other languages much more readable using lambda functions. And those work for any arguments, not just the last one(s).
It's a shame the only language that did partial application well is, weirdly, Python.
I guess you were talking about `functools.partial`, which is basically the same as currying and also only works on the last arguments. It's better to use lambda functions.
Also Python is far from the only language to have a function like that, e.g. see C++'s `std::bind` which nobody* uses since lambdas were supported.
*standard HN disclaimer
I was talking about `functools.partial` yes, but it can work on any arguments in order, using keyword arguments.
e.g.
def copy(source, dest):
.....
copy_to_temp = partial(copy, dest="/tmp/")
copy_from_temp = partial(copy, source="/tmp/")how is `add a b c = a + b + c` being curried an issue to you?
or (where available) sections
After like ten or fifteen hours of trying to understand what currying is, I still have no idea, and frankly don't care. If I see it in a codebase it'd just be a big red flag to avoid that job altogether.
Example
add 1 2 // add is curried, you can use it like this, the "normal" way, returns 3
p = add 1 // since add is curried I can also provide just the first argument
p 2 // and then apply the last argument to the intermediate results, returns 3
What is the point of using curried functions in JS? I am not really sure. It is not very ergonomic and I wouldn't like to use them in general. Maybe for some specific things it could be useful.In Haskell curried form is the default and the syntax and semantics really suits it. In JS non-curried is the default and it just looks odd, and you need libraries to support it. That library you mentioned doesn't look nice to use.
https://wiki.haskell.org/Pointfree
There is a sliding scale and even at the Haskellers have a limit of how much point-free they can take.
In JavaScript use of the style is problematic in another way: unlike Haskell in JS the length of the argument list is variable, which means that if someone adds another argument to either the caller or callee it can break the code in subtle and unexpected ways.
For this reason it’s good practice to always wrap functions being passed as arguments to another function in a lambda expression.
i.e instead of writing: g(f), you should usually write: g(x => f(x)) unless you have good reason to believe that g(f) is safe. This makes it difficult to use point-free style at all in JS.
For example arr.map(f) is generally unsafe in JS because if `f` adds an extra default argument of type number then your code will break and even TypeScript won’t let you know.
Things like currying are fun but like anything that encourages gratuitously deep call trees, they wreck your locality of reference (as a developer) and force you to 'decompile' the code in your head in order to understand it. I'm sure that a top level developer would be able to write curried JS in such a way that it was clear and readable to another top level developer, but that's not the point. The code's not for you, it's for newbie who gets stuck with it when you move on.
What if you forget, not in quotes, to give the second argument? Why on earth would you want to get a type error in a completely different part of the code because you got a function instead of an integer? Wouldn't it be desirable to have the compiler just tell you that you forgot the second argument where you forgot the second argument?
Is it really valuable to be able to do:
p = add 1
...instead of: inc = (\x -> add 1 x)
...or, heaven forbid: inc x = add 1 x
...?I mean, I get the idea, they're following the lambda calculus, but this is one of the things that should have been dropped when they started to expand the lambda calculus to a general purpose programming language.
I will get a type error and it will take me 2-3 seconds to figure out what it is about.
> Why on earth would you want to get a type error in a completely different part of the code because you got a function instead of an integer?
Why would it be in a completely different part of the code? At most it would be 2 lines away, but usually on the same line.
But I don't think this is a problem in practice for whatever reason. Haskell does have a lot of "big scary type error, wtf" type problems, but not from currying. Or at least it did have when I last used it 5 years ago, it may have improved in the compiler error message front.
Also it is better than JS anyway (low bar):
> function add(a,b) {return a + b}; add(1);
<- NaNI have doubts on whether this is a sincere attempt at understanding the concept. The linked wiki page is like a five minute read and that's enough to understand the concept at a user's level.
What I suspect is that something else is tripping you up and causing code readability issues; but since you didn't know what currying is you incorrectly ascribed currying as the problem.
Software is in good hands.
When you're writing Haskell, you should write idiomatic Haskell. Currying is part of that. It's a trivial concept and we use it liberally at work. If you're writing JavaScript though, I think it's a different story. I don't think JavaScript lends itself to FP in the way that Haskell or Elm does, and trying to make it do that only makes a project harder to work on.
The entire codebase was like that. It stood out to me as the work of someone who was very smart but worked alone and never had to work with a team, and never considered what someone trying to retrace his mental process would have to go through. He left zero documentation or comments, built the whole thing in a rush, sold it to another company, and we were the ones hired later to clean up his mess.
Some of it was very good. He was really good at efficiently encoding low level network traffic over packet encodings he invented or heavily modified. Seemed like he would've been a brilliant signals engineer or cryptologist. But having to work with his ordinary business logic code was pretty nightmarish, if interesting from a reverse engineering and psychology point of view.
It's just not how I would ever want to write code meant for mere mortals. But then again, he's a multi millionaire now and I'm a rando nobody living paycheck to paycheck, so I'm in no place to judge lol.
f a b = g(a,b) = f' b a
(x^2)^3 = x^(2*3) = (x^3)^2just my 2 ct
Maybe you could recall which learning materials you used?
Dynamically typed functional retrofit on with no type checking though? Hell no, that's a write-once read-never mess of unmaintainable shite.
(I also have been on a team with The Guy Who Wanted To Ramda, and I'm someone who writes build scripts in ocaml)
Inheriting that codebase felt like watching one of those serial killer dramas... obviously a really smart guy, but with a psychology unlike most people I've ever met, and really hard to follow as a normal person. I still see him with a mixture of respect, awe, curiosity, and wonder.
The thing is, none of the stuff he gave is was actually complicated. It's just a basic business dashboard. But he reinvented almost every single part of it in totally nonstandard ways that the whole project was less about coding and more about anthropology and forensic psychology.
Uncurried:
((x, y) => x * y)(3, 5) === 15
Curried:
(x => y => x * y)(3)(5) === 15
If you don't understand that, your problem is that you don't understand anonymous functions (lambdas), not that you don't understand currying.
https://en.wikipedia.org/wiki/Tacit_programming
https://medium.com/@jesterxl/real-world-uses-of-tacit-progra...
when you use tacit programming and currying together you can write code in a "bash-like" pipe style which not only makes the program more readable but also is less error prone.
You can make code much shorter by removing all the application-specific names and only using very abstract, domain-independent names or symbols. The result can be seen in complicated regular expressions, array languages, bash scripts, and so on. In the wrong hands, these are all notoriously unreadable.
But you can also go to the other extreme and give every little thing a very long name, and that’s less readable in its own way. Bob Nystrom wrote a nice article about how to combat that tendency. [1]
Naming things is an art. In functional languages, let expressions are convenient and useful. When you feel like you don’t want to define another function, sometimes it’s better to resist that tendency and think about a better name.
[1] https://journal.stuffwithstuff.com/2016/06/16/long-names-are...
When it comes to names, the binding and lexical scope and position in the AST helps me read the code more than the English pronunciation.
Tbh if I have a stream of English words in my head reading Haskell, it's probably already meh code at best :S
I'd say I see more Haskell code made unreadable due to over-naming than under-naming in the wild (i.e. industry)
high level abstraction can make you very productive, but it can also be rather unreadable. e.g. two code snippets in python (yes this is valid python code with some operator overloading):
# compute pi by drawing random numbers in a circle
1000000 >> ψ( ψ(χ>>op("(x**2+y**2)**0.5<1")@rlµ<<χ)>>Σ*4>> _/_)
or this: # 10 fibonacci numbers
[x:=[1,1]] + [x := [x[1], sum(x)] for i in range(10)]
I would of course not use that in production code, but for a rapid prototype it is priceless to do something like this in python.just my 2 ct
x = y 3
vs
x = partial y 3
I would vastly prefer the latter. And if you do it a lot you could have a symbol for it in your language.
Your examples are unrelated to currying though...
Reading through these comments, it's clear that currying isn't clearly understood, which makes me doubt it's worth the cognitive load to use in a codebase.
In my limited Haskell experience, you can mostly ignore that functions are curried, but every once in a while, someone uses it, and it has never, in my experience, made the code easier to understand, because the currying happens implicitly.
The more general case of currying is partial application, where instead of a function taking only its first argument and returning a function that takes its next argument, you can apply a function any of it's arguments and return a function that takes the remaining arguments. So if you have:
div x y = x / y
Then: invert = (\x -> div 1 x)
-- invert is a partial application of div to the 1 as first argument
halve = (\x -> div x 2)
-- halve is a partial application of div to 2 as the second argument
Obviously, the first one could be done with currying. What makes partial application better in my opinion is that it's explicit about what's happening, and doesn't happen without you asking it to. gears = filter ((==2) . length)
. map (neighbouringNumbers numbers)
$ filter ((=='*') . fst) symbols
which without currying would have to look like gears = (\xs -> filter ((\x -> x == 2) . length) xs)
. (\xs -> map (\x -> neighbouringNumbers numbers x) xs)
$ filter (\(c,_) -> c == '*') symbols
It just makes partial application a lot easier, especially when this kind of code pops up all over the place.Eh, but that's my point: I want less cognitive load. Currying is another thing that I have to keep in the back of my mind, and Haskell already has way too many of those, and it's not a particularly useful thing. I've got limited space in the back of my mind for things and if I'm going to keep things in the back of my mind I want them to be useful. I mean, if your argument in favor of currying is that it saved you a few keystrokes in that example, color me unimpressed.
Maybe I'm just too stupid to understand easily, but the "simple" example you're giving is taking me a while to understand. If a junior dev on my team submitted that in a PR I'd send it back asking them to break it up into a few smaller named functions and probably not use a partial application at all. Something like "I know it's fun to be clever but let's make this easier for the next person who has to figure out what it does".
I guess what I'm saying is that for that example it seems like you're going for tersity rather than clarity for future readers of the code. If you were going for clarity you probably wouldn't write it either of the ways you've given.
And in big projects clarity is the number 1 concern[1]. In toy examples like this I can slog through and figure something like this out, but when it's 30 functions written like this, all calling each other in the most clever ways possible, nobody can figure it out.
[1] EDIT: Okay #2 after correctness perhaps. But it becomes hard to achieve correctness without clarity as a project grows.
gears = filter ((==2) . length)
. map (neighbouringNumbers numbers)
$ filter ((=='*') . fst) symbols
If this Haskell code does not look clear, it's because people are unfamiliar with point-free style, not because the this code is badly written, and especially not because the reader is stupid.The given Haskell code reads naturally to me now. (I'm only a little uncertain because I can't write Haskell.) It would have been line noise to me before before point-free style clicked.
I tend to read Haskell code in articles from right to left, and it reads: "Choose the symbols whose first letter is '*', get their respective (neighboringNumbers numbers), and choose the results whose length is 2". I read (neighboringNumbers numbers) as if it were a noun.
I don't know how this clicked, but I'm pretty sure it has nothing to do with stupidity. Perhaps it was by chance, or perhaps it was by banging my head against the wall enough times.
Would I introduce point-free style in a JS codebase? Probably not. People are unfamiliar with this kind of style. Would I introduce this style in a Haskell codebase? Almost certainly, because it's clear and I think it reflects how Haskell programmers think.
Which is because lambda calculus does not have functions with more than one parameter, I guess.
And in the lambda calculus, it makes a ton of sense, because it allows you to break proofs into smaller chunks more easily.
But in a general-purpose programming language where the proofs are automated, I think this just makes the code less communicative of programmer intent.
This had to be said! Sure you can make the argument that this improves your productivity as a coder, or makes the code more concise, but to someone coming along cold and trying to pick apart your code to fix something it's going to be a nightmare.
Having gone through it, I highly recommend the book; especially to anyone knowledgeable about any 2 and interested in the third.
I love Haskell. I love writing it, and reading it. Haskell is a beautiful programming language. One where I felt immediately at home in and comforted by.
Currying is one of the foundational concepts of the language, but I do think it is one aspect of the language the community treats excessively sacredly.
In Haskell, function composition has right associativity. What this means, in the event of a function that takes in 3 Integers as arguments and returns a Double would have a type definition of:
FN_NAME :: Int -> Int -> Int -> Double
The right associativity then also means this is equivalent to these type definition: fn0 :: Int -> Int -> Int -> Double
fn0 x y z = (fromIntegral (x + y)) / (fromIntegral z)
fn1 :: Int -> (Int -> Int -> Double)
fn1 x y z = (fromIntegral (x + y)) / (fromIntegral z)
fn2 :: Int -> (Int -> (Int -> Double))
fn2 x y z = (fromIntegral (x + y)) / (fromIntegral z)
ghci> fn0 1 2 3 -- 1.0
ghci> fn1 1 2 3 -- 1.0
ghci> fn2 1 2 3 --1.0
This is currying in action. A function that takes three arguments is the same as a function that takes one argument and passes it to function that takes two arguments.As I understand it, the compiler sees ALL functions as a composition of functions of one input.
This is pretty cool, and a powerful foundation to build on. Where I take a bit of issue is when the Haskell community allows the rigor of the type definition to carry some of the weight of the expressiveness of the function definition.
Each function definition ('=') pairs with a type definition ('::'), as the ones above, ie. an example from the promoted book:
type R = Double
type VecDerivative = (R -> Vec) -> R -> Vec
vecDerivative :: R -> VecDerivative
vecDerivative dt v t = (((v (t + dt/2)) ^-^ (v (t - dt/2))) ^/ dt)
velFromPos :: R -- dt
-> (R -> Vec) -- position function
-> (R -> Vec) -- velocity function
velFromPos = vecDerivative
The second function definition: "velFromPos = vecDerivative" ; is equal to saying, "velFromPos dt v t = vecDerivative dt v t". Haskell seems to allows this syntactical ~implicit argument passing because of it's reverence for currying. -- random example of 'vector-valued function'
v1 :: R -> Vec
v1 t = ((2 *^ (t**2 *^ iHat)) ^+^ (3 *^ (t**3 *^ jHat)) ^+^ (t**4 *^ kHat))
ghci> vecDerivative 0.01 v1 1 -- vec 3.999999999999937 9.000074999999885 4.000099999999962
ghci> velFromPos 0.01 v1 1 -- vec 3.999999999999937 9.000074999999885 4.000099999999962
This has some interesting effects, such as displayed above where the use of currying makes it explicitly clear that calculating the velocity is the exact same thing as calculating the derivative of position.But I always felt this ~implicit syntax is needlessly aggressive to newcomers.
I also pathologically write my Haskell code like a Lisp because the Haskell community's celebration of the complex precedence structure of its order of operations causes practitioners to appear, to my eyes, over confident in their ability to sight read their own work's order of operations. ;P
ghci> sqrt 2 + 1 * 3 + 3 * 2 + 1 / 7 -- 10.557070705230238
ghci> ((sqrt 2) + ((1 * 3) + ((3*2) + (1 / 7)))) -- 10.557070705230238
I will forever think the second is easier to read, but if you look at many Haskell code bases you will see stuff like the first all over the place, and I have been unable to find a reason why the implicit function arguments and lack of parenthesis syntax is considered idiomatic.In the face of the ability to write the functions explicitly and with expressive parentheses, it seems the answer is "because you can".
>>> math.sqrt(2) + 1 * 3 + 3 * 2 + 1 / 7
10.557070705230238
The only difference I see is the parentheses used for function application in python.Due to Haskell's rigor in regard negative numbers:
ghci> -1 + 2
1
ghci> 2 + -1
<interactive>:12:1: error:
Precedence parsing error
cannot mix ‘+’ [infixl 6] and prefix `-' [infixl 6] in the same infix expression
ghci> 2 + (-1)
1
ghci> -1 * 3
-3
ghci> 3^-1
<interactive>:3:2: error:
• Variable not in scope: (^-) :: t0 -> t1 -> t
• Perhaps you meant one of these:
‘^’ (imported from Prelude), ‘-’ (imported from Prelude),
‘^^’ (imported from Prelude)
ghci> 3^^-1
<interactive>:4:2: error:
• Variable not in scope: (^^-) :: t0 -> t1 -> t
• Perhaps you meant ‘^^’ (imported from Prelude)
ghci> 3**-1
<interactive>:5:2: error:
• Variable not in scope: (**-) :: t0 -> t1 -> t
• Perhaps you meant ‘**’ (imported from Prelude)
ghci> 3**(-1)
0.3333333333333333
ghci> sqrt 2 + 1 * 3 + 3 * 2 + 1 / 7
10.557070705230238
ghci> sqrt $ 2 + 1 * 3 + 3 * 2 + 1 / 7
3.3380918415851206
ghci> -sqrt 2 + 1 * 3 + 3 * 2 + 1 / 7
7.728643580484048
ghci> -sqrt $ 2 + 1 * 3 + 3 * 2 + 1 / 7
<interactive>:25:1: error:
• Non type-variable argument in the constraint: Num (a -> a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall {a}. (Floating a, Num (a -> a)) => a
ghci> sin -1
<interactive>:7:1: error:
• Non type-variable argument in the constraint: Num (a -> a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall {a}. (Floating a, Num (a -> a)) => a -> a
ghci> (sin -1)
<interactive>:10:1: error:
• Non type-variable argument in the constraint: Num (a -> a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall {a}. (Floating a, Num (a -> a)) => a -> a
ghci> sin (-1) -- -0.8414709848078965
Let's see, ghci> (sin (-1)) -- -0.8414709848078965
Ahh, now that's better.