Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ramda.js - Ramda chain usage

From the documentation:

var duplicate = n => [n, n];
R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]

The first example is very straight forward, it applies duplicate() to every element in the array and concatenates the result. But I am having trouble understanding the second example. How exactly is it mapping R.append + R.head over the array? Can someone please provide a step by step explanation for the second example ?

I am familiar with compose and currying.

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The second example is showing how R.chain can be used things other than arrays, such as functions (or anything implementing the Fantasy Land chain spec).

If the concept of mapping and then concatenating an array is familiar to you, you can think of mapping a function over another function as plain function composition. The concatenating part will require further explanation.

R.chain declares its signature as:

Chain m => (a → m b) → m a → m b

For arrays, we can swap the m with [] to get:

(a → [b]) → [a] → [b]

For functions that receive some argument r, it becomes:

(a → r → b) → (r → a) → (r → b)

So with only the knowledge of those types available, the only way to produce the final r → b function is to do the following:

  • Pass the received argument r to the second function to produce an a
  • Apply both the new a and the original r to the first function to produce the resulting b

Or in code:

// specialised to functions
const chain = (firstFn, secondFn) =>
  x => firstFn(secondFn(x), x)

Swapping in the functions from the example, you can see it becomes:

x => R.append(R.head(x), x)

If you are familiar with R.converge then this is effectively:

R.converge(firstFn, [secondFn, R.identity])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...