高阶函数有什么有趣的用法? [英] What are some interesting uses of higher-order functions?

查看:99
本文介绍了高阶函数有什么有趣的用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在做一个函数式编程课程,我很喜欢高级函数和函数作为一等公民的概念。然而,我还不能想到许多实际上有用的,概念上的惊人的,或者仅仅是简单有趣的高阶函数。 (除了典型的和非常枯燥的 map filter 等函数)。

您知道这些有趣功能的例子吗?函数,返回函数列表的函数(?)等。

我很欣赏Haskell中的例子,这是我目前学习的语言:)

那么你注意到Haskell没有循环的语法吗?没有,而 do 。因为这些都是高阶函数:

  map ::(a  - > b) - > [a]  - > [b] 

foldr ::(a - > b - > b) - > b - > [a] - > b

filter ::(a - > Bool) - > [a] - > [a]

unfoldr ::(b - > Maybe(a,b)) - > b - > [a]

iterate ::(a - > a) - > a - > [a]

高阶函数取代了控制结构语言中对语法进行烘焙的需要,这意味着几乎每个Haskell程序都使用这些函数 - 使它们非常有用!



它们是实现良好抽象的第一步,因为我们现在可以将自定义行为插入通用目的骨架函数。



特别是, monads 只是因为我们可以链接在一起,并且可以操作函数来创建程序。



事实是,当它是一阶时,生活是非常无聊的。一旦你有更高的订单,编程才会变得有趣。


I'm currently doing a Functional Programming course and I'm quite amused by the concept of higher-order functions and functions as first class citizens. However, I can't yet think of many practically useful, conceptually amazing, or just plain interesting higher-order functions. (Besides the typical and rather dull map, filter, etc functions).

Do you know examples of such interesting functions?

Maybe functions that return functions, functions that return lists of functions (?), etc.

I'd appreciate examples in Haskell, which is the language I'm currently learning :)

解决方案

Well, you notice that Haskell has no syntax for loops? No while or do or for. Because these are all just higher-order functions:

 map :: (a -> b) -> [a] -> [b]

 foldr :: (a -> b -> b) -> b -> [a] -> b

 filter :: (a -> Bool) -> [a] -> [a]

 unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

 iterate :: (a -> a) -> a -> [a]

Higher-order functions replace the need for baked in syntax in the language for control structures, meaning pretty much every Haskell program uses these functions -- making them quite useful!

They are the first step towards good abstraction because we can now plug custom behavior into a general purpose skeleton function.

In particular, monads are only possible because we can chain together, and manipulate functions, to create programs.

The fact is, life is pretty boring when it is first-order. Programming only gets interesting once you have higher-order.

这篇关于高阶函数有什么有趣的用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆