什么是“无点”风格(在函数式编程中)?
-
09-09-2019 - |
解决方案
只要看看维基百科文章让你的定义:
隐性编程(自由点编程)是一个编程范例,其中一功能定义不包括关于它的参数,使用组合子和功能的组合物[...]代替变量的信息。
Haskell的示例:
传统(明确指定参数):
sum (x:xs) = x + (sum xs)
sum [] = 0
点 - 自由(sum
不具有任何显式的参数 - 它只是一个与+
从0开始倍):
sum = foldr (+) 0
或者更简单:而是g(x) = f(x)
的,你可以只写g = f
所以,是:它密切相关的讨好(或类似的功能的组合物操作)
。其他提示
自由点式是指所定义的函数的参数没有被明确提到的,该功能是通过功能组合物定义的。
如果你有两个功能,如
square :: a -> a
square x = x*x
inc :: a -> a
inc x = x+1
如果你想这两个功能结合起来,一个计算x*x+1
,您可以定义为“点满”是这样的:
f :: a -> a
f x = inc (square x)
在自由点的替代将不谈论参数x
:
f :: a -> a
f = inc . square
一个的JavaScript示例:
//not pointfree cause we receive args
var initials = function(name) {
return name.split(' ').map(compose(toUpperCase, head)).join('. ');
};
const compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];
const join = m => m.join();
//pointfree
var initials = compose(join('. '), map(compose(toUpperCase, head)), split(' '));
initials("hunter stockton thompson");
// 'H. S. T'
点自由的风格意味着代码没有明确提到它的参数,即使它们的存在和正在使用。
这个作品在Haskell由于单向函数的工作。
例如:
myTake = take
返回一个函数,它接受一个参数,因此没有理由显式类型的参数,除非你只是想太多。
下面是在打字稿一个实例,没有任何其他文库:
interface Transaction {
amount: number;
}
class Test {
public getPositiveNumbers(transactions: Transaction[]) {
return transactions.filter(this.isPositive);
//return transactions.filter((transaction: {amount: number} => transaction.amount > 0));
}
public getBigNumbers(transactions: Transaction[]) {
// point-free
return transactions.filter(this.moreThan(10));
// not point-free
// return transactions.filter((transaction: any) => transaction.amount > 10);
}
private isPositive(transaction: Transaction) {
return transactions.amount > 0;
}
private moreThan(amount: number) {
return (transaction: Transaction) => {
return transactions.amount > amount;
}
}
}
您可以看到免费的点式更“流畅”,更容易阅读。
不隶属于 StackOverflow