0

I'm trying to learn functional programming in JavaScript, and I can't wrap my head around this higher-order function. I don't understand why calling g(1,2,3,4) results in [1]. I tried doing console.log("arg: ", arg) as below, and I don't understand why arg in the console.log is 1. Where does arg come from? How is arg passed to funcation one(arg)? Does it have anything to do with curry? Can someone explain it in a very simple and beginning level way?

function unary(fn) {
        return function one(arg) {
        console.log("arg: ", arg)
            return fn(arg)
        }
}

function f(...args) {
    return args
}
    
var g =  unary(f)
g(1,2,3,4) // [1]
Sophia
  • 55
  • 7
  • 2
    The example is a bit strange. It’s passing four arguments to a function that only accepts one and ignores the rest. _“Where does `arg` come from?”_ — It’s the `1` from `g(1,2,3,4)`. This call is equivalent to `g(1)`. – Sebastian Simon Oct 12 '22 at 23:14
  • Thanks for your answer. Where in the functions are 2,3 and 4 shopped out? – Sophia Oct 12 '22 at 23:20
  • You could also return the `function one(arg1, arg2, arg3) { return fn(arg) }` to make it more clear where the other arguments go – Bergi Oct 12 '22 at 23:29
  • Look at the type to get rid of the noise (pseudo annotation): `unary :: (a -> b) -> a -> b`. `unary` takes a function `(a -> b)` as an argument and returns another function `a -> b`. This other function takes an argument `a` and applies it with the function argument. The other arguments are just ignored. `unary` is thus an applicator that enforces a single argument. –  Oct 13 '22 at 07:58

0 Answers0