-3

Can someone please explained the steps that are happening in this code particularly the marked part. Is it recursive how does it slot together..?

const func = x => k => func (k (x))
//                     ^^^^^^^^^^^^      
const add = x => y =>
  x + y

func(1)(add(2))(add(2))(console.log);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Lulgik
  • 17
  • 1
  • Looks more like a coding curiosity, or minified/mangled code. Anyway it's very hard to understand, nobody would ever write this kind of things – Jeremy Thille Jan 08 '21 at 15:38
  • 2
    @JeremyThille it's a fairly standard functional code. Hardly something nobody would write or even much out of the ordinary. – VLAZ Jan 08 '21 at 15:43
  • Well anyway I don't think I'd ever write something that twisted – Jeremy Thille Jan 08 '21 at 15:55
  • 2
    This is recursive function application you cannot escape from. The basic application pattern is `func(1) (inc) (log);` logs 2, `func(1) (inc) (inc) (log)` logs 3, etc. The underlying structure that is build looks like `inc(inc(...(1)))`. –  Jan 08 '21 at 16:14

1 Answers1

1

As it stands, func doesn't type check because we can't construct the infinite type t a ~ (a -> b) -> t b. However, we can get around that restriction by creating a new data type as follows.

// Chain :: (forall b. (a -> b) -> Chain b) -> Chain a
const Chain = chain => ({ chain });

// func :: a -> Chain a
const func = x => Chain(k => func(k(x)));

// add :: Number -> Number -> Number
const add = x => y => x + y;

// trace :: a -> a
const trace = x => {
    console.log(x);
    return x;
};

// Chain Number
func(1).chain(add(2)).chain(add(2)).chain(trace);

Now, Chain is a very weird data type. It's an infinite chain of type-aligned functions.

   Chain a
 = (a -> b) -> Chain b
 = (a -> b) -> (b -> c) -> Chain c
 = (a -> b) -> (b -> c) -> (c -> d) -> Chain d
 -- ad infinitum

However, this data type is not very useful for purely functional programming because you can never consume a Chain value. The only way you can make use of intermediate results in the chain is by using an impure function like trace. I'd suggest that you avoid such useless data types altogether.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299