我正在探索一些用于函数式编程的 JavaScript 库,例如 Ramda、Sanctuary 等。我还检查了他们的管道和组合函数的链接和组合。但他们不能像下面这样同时使用 x 和 y 来产生最终值。
for {
x <- xs
y <- ys
} yield Point(x, y)
Sanctuary 和类似的库已经实现了单子数据类型。我想知道他们是否也支持诸如 do-notation 或 for-compression 之类的东西。可能他们已经有了,但我只是找不到该功能的正确名称。或者那些库有自己的方法来解决类似的问题。
基本上,我希望能够使用 do/for 之类的构造来删除结尾处的嵌套 flatMap 调用:
const S = require('sanctuary')
class Book {
constructor(title, authors) {
this.title = title
this.authors = authors
}
}
class Movie {
constructor(title) {
this.title = title
}
}
const books = [new Book("FP in Scala", ["Chiusano", "Bjarnason"])
, new Book("The Hobbit", ["Tolkien"])
, new Book("Modern Java in Action", ["Urma", "Fusco", "Mycroft"])]
console.log(books)
console.log(books.map(b => b.title))
console.log(
books.map(b => b.title)
.filter(t => t.includes('Scala'))
.length
)
function bookAdaptations(author) {
if (author === "Tolkien") {
return [new Movie("An Unexpected Journey")
, new Movie("The Desolation of Smaug")]
} else {
return []
}
}
console.log(bookAdaptations("Tolkien"))
console.log(
books.flatMap(b => b.authors)
.flatMap(a => bookAdaptations(a))
)
console.log(
books.flatMap(book => (
book.authors.flatMap(author => (
bookAdaptations(author).map(movie =>
`You may like ${movie.title}, `
+ `because you liked ${author}'s ${book.title}`
)
)
)
))
)