简体   繁体   English

Haskell在数据结构中存储功能-用例

[英]Haskell storing functions in data structures - use cases

I was going through the Software Foundations book ( http://www.cis.upenn.edu/~bcpierce/sf/Basics.html ). 我正在阅读《软件基础》一书( http://www.cis.upenn.edu/~bcpierce/sf/Basics.html )。 In the second paragraph of Introduction , it is mentioned that as functions are treated as first class values, they can be stored in a data structure. 简介的第二段中,提到将函数视为第一类值,因此可以将它们存储在数据结构中。 A quick Google search for the applications of this turned up acid-state ( http://acid-state.seize.it/ ) which probably uses this for storing functions (please correct me if I am wrong). Google快速搜索了此酸性状态的应用程序( http://acid-state.seize.it/ ),该酸性状态可能使用此状态存储函数(如果我错了,请纠正我)。 Are there any other applications in which storing functions as data in data structures is/can be used? 是否有其他应用程序可以/可以使用将功能作为数据存储在数据结构中? Is storing functions as data a common pattern in Haskell? 将函数作为数据存储是Haskell的一种常见模式吗? Thanks in advance. 提前致谢。

Edit: I am aware of the higher order functions. 编辑:我知道高阶函数。

A simple and easily-used functions-in-data-structure example is that of having a record containing functions (and possibly data). 一个简单易用的数据结构函数示例是具有包含函数(可能还有数据)的记录的示例。

A good example is in Luke Palmer's blog post Haskell Antipattern: Existential Typeclass where he explains that rather than try to reproduce an OO-like class for widgets, with many instances and then store your UI widgets in an existentially quantified list, you're better off making a record of the actual functions you'll use and returning that instead of retaining your original datatype - once you're existentially quantified, you can't get at the original datatype anyway, so you don't lose anything in expressiveness, but gain a lot in manipulatability. 一个很好的例子是卢克·帕尔默(Luke Palmer)的博客文章Haskell Antipattern:Existential Typeclass ,他在其中解释说,与其尝试为具有许多实例的Widget再现类似于OO的类,然后将UI Widget存储在一个存在的量化列表中,不如说是更好的。记录要使用的实际函数并返回该值,而不是保留原始数据类型-对其进行定量量化后,无论如何您都无法获得原始数据类型,因此您不会在表现力上损失任何东西,但获得了很多可操作性。 He concludes 他总结

Functions are the masters of reuse: when you use an advanced feature, you need a yet more advanced feature to abstract over it (think: classes < existential types < universally quantified constraints < unknown). 函数是重用的基础:使用高级功能时,您需要一个更高级的功能对其进行抽象(请考虑:类<存在类型<普遍量化的约束<未知)。 But all you need to abstract over a function is another function. 但是,您需要抽象的一个功能是另一个功能。

This means that we can write higher-order functions to deal with those functions, and pass them around and manipulate them easily, since they're data. 这意味着我们可以编写高阶函数来处理这些函数,并传递它们并轻松地对其进行操作,因为它们是数据。

一流的功能非常有用-我认为它们的主要用例是在更高阶的函数中 ,它可以简化许多问题,这些问题需要使用其他语言(例如Java)编写更复杂的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM