Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - What is going on in this code ? I do not understand how this works could someone please step me through this

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...