使用在它所使用的函数范围之外声明的函数是否违反了诸如不变性之类的功能原则?或者是专门指数组、字符串等数据。
例如:
var data ["cat", "dog", "bird"];
function doThing (val) {
return val + ", go away!"
}
function alterData (data) {
return data.map(doThing);
}
alterData(data);
上面的代码可以接受吗?还是需要将“doThing”函数作为参数传递给 alterData 函数?
我感到困惑的原因是,在函数式编程示例中,我经常看到所使用的语言的 native 函数没有首先传递给函数。但是,这些示例从来都不够复杂,无法展示如何使用函数库。
问候
最佳答案
在这方面,函数式编程与过程式编程没有什么不同——你编写的定义可以在它们范围内的任何地方重用。您可以通过各种机制控制范围内的内容,例如模块定义、模块导出列表和模块导入。例如(在 Haskell 中):
module My.Module
-- List of definitions exported from this module
( doThing
, alterData
) where
-- Any definitions exported from `My.Other.Module` will be in scope
-- in this one
import My.Other.Module
-- Can't name this `data` because it's a reserved word in Haskell
yourData :: [String]
yourData = ["cat", "dog", "bird"]
doThing :: String -> String
doThing val = val ++ ", go away!"
alterData :: [String] -> [String]
alterData strings = map doThings strings
关于functional-programming - 在函数式编程中,一个函数可以调用另一个在其范围之外声明且未作为参数传递的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33440065/