In functional programming, can a function call another function that has been declared outside its scope and not passed as a parameter?

Does a function declared outside the scope of the function that it uses violates a Functional Principle, such as immutability? Or it refers specifically to data such as arrays, strings, etc.

For example:

var data ["cat", "dog", "bird"]; function doThing (val) { return val + ", go away!" } function alterData (data) { return data.map(doThing); } alterData(data); 

Would the above code be acceptable? or should the "doThing" function be passed to the alterData function as an argument?

The reason I got confused is that in the examples of functional programming, I often see functions that are native to the language used, not being the first function passed. However, the examples are never complex enough to show how to work with the library of functions.

Hi

+7
functional-programming
source share
3 answers

Functional programming is no different from procedural programming in this respect - you write definitions that you can use anywhere they are. You control that in an area where with various mechanisms, such as module definitions, module export lists, and module import. So for example (in 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 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 
+1
source share

TL; DR

This is great to rely on scope in FP code.


Invariance means that something represented by a name cannot change its meaning. However, I would not call this the β€œprinciple” of functional programming.

In any case, this is not at all related to the definition of a region. Passing things as arguments makes sense if you want to parameterize a function by another function - essentially making it a higher order function. A good example of this is fold (also known as reduce ), but map also one.

In your case, the alterData function alterData not add much value. map ping is something so common over something that it is usually better to provide only a singleton function, since it is, in principle, more reusable.

If you went doThing to alterData , you will make this function useless; why would i use it if i could just use map ? However, packaging an operation along with a display can sometimes be a useful abstraction.

+1
source share

Well, doThing way it is. You need to do this:

 var data = ["cat", "dog", "bird"]; var doThing = function (val) { return val + ", go away!" } function alterData (data) { return data.map(doThing); } alterData(data); 
0
source share

All Articles