Any difference between First Class Function and High Order Function - functional-programming

I'm wondering whether/what difference between First Class Function and High Order Function.
I read through those two wiki pages and they looks rather similar.
If they talking about same, why need two terminologies?
Tried to google but have not found any useful thing.

There is a difference. When you say that a language has first-class functions, it means that the language treats functions as values – that you can assign a function into a variable, pass it around etc. Higher-order functions are functions that work on other functions, meaning that they take one or more functions as an argument and can also return a function.
The “higher-order” concept can be applied to functions in general, like functions in the mathematical sense. The “first-class” concept only has to do with functions in programming languages. It’s seldom used when referring to a function, such as “a first-class function”. It’s much more common to say that “a language has/hasn’t first-class function support”.
The two things are closely related, as it’s hard to imagine a language with first-class functions that would not also support higher-order functions, and conversely a language with higher-order functions but without first-class function support.

First class functions are functions that are treated like an object (or are assignable to a variable).
Higher order functions are functions that take at least one first class function as a parameter, or return at least one first class function.

They're different.
First class functions
Values in a language that are handled uniformly throughout are called "first class". They may be stored in data structures, passed as arguments, or used in control structures.
Languages which support values with function types, and treat them the same as non-function values, can be said to have "first class functions".
Higher order functions
One of the consequences of having first class functions is that you should be able to pass a function as an argument to another function. The latter function is now "higher order". It is a function that takes a function as an argument.
The canonical example is "map"
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
That is, it takes a function, and an array, and returns a new array with the function applied to each element.
Functional languages -- languages where functions are the primary means of building programs -- all have first class functions. Most also have higher order functions (very rare exceptions being languages like Excel, which can be said to be functional, but not higher order).

In addition to the previous answers, note that a language with first-class functions automatically enables the expression of higher-order functions (because you can pass functions as parameters like any other value).
On the other hand, you can imagine languages that support higher-order functions, but do not make functions first-class (and where parameters that are functions are treated specially, and different from "ordinary" value parameters).
So the presence of first-class functions (as a language feature) implies the presence of higher-order functions, but not the other way round.

First Class functions can:
Be stored in variables
Be returned from a function.
Be passed as arguments into another function.
High Order Function is a function that returns another function.
For example:
function highOrderFunc() {
return function () {
alert('hello');
};
}

First class function:
When we pass function as an argument of another function called first class function.
The ability to use function as a values known as first class function.
var a = function(parameter){
return function(){
}
}
console.log(a())
Higher-Order Function:
A function that receives another function as an argument or that returns a new function or both is called Higher-order functions. Higher-order functions are only possible because of the First-class function.

First class functions mean everything you can do with other types(variables, booleans, numbers...), you can do it with functions.
For example Assign them to variables, pass it around, create them on fly.

First-class Function is a general term.
High Order Function is a variation of First-class Function, it's a subspecies of First-class Function.
High Order Function is a function that returns a function or takes other functions as arguments.
Example of High Order Function:
function sayHello() {
return () => {
console.log("Hello!");
};
}
But at the same, we can call this function like First-class Function. Only the answer will be not so clear as if you said the High Order Function, because it's a more concrete term.
function sayHello() {
return () => {
console.log("Hello!");
};
}
Resource: developer.mozilla
In easy words, there is a brand Bentley, it's a general term.
Bentley has models:
Continental (it's Bentley, it's just a more concrete term)
Flying Spur (it's Bentley, it's just a more concrete term)
Bentayga (it's Bentley, it's just a more concrete term)

A first-class function is a function that is treated as a variable. In addition, they can be used as arguments for other functions.
A function in JavaScript is treated as a first-class citizen. Therefore, functions are also objects simply because they are values.
As in JavaScript, functions are considered values or objects.
const Person = {
dance:(name) => {
return `${name} can dance`
},
walk:(name) => {
return `I am sure ${name} can walk `
},
}
console.log(Person.dance("John"));
console.log(Person.walk("John"));
In higher-order functions, other functions are taken as arguments (callbacks) or returned as results.
There is a lot of use for this concept in JavaScript.
Functions of higher order include:
map
sort
filter
map example-
without higher order
const numbers = [1, 2, 3, 4, 5];
function addOneMore(array, newArr = []) {
for (let i = 0; i < array.length; i++) {
newArr.push(array[i] + 1);
}
return newArr;
}
const outputData = addOneMore(numbers);
console.log(outputData);
with high order function, map()
const numbers = [1, 2, 3, 4, 5];
const outputData = numbers.map((number) => number + 1);
console.log(outputData);

Related

What's the difference between calling a function and functional programming

I'm referring to this article https://codeburst.io/a-beginner-friendly-intro-to-functional-programming-4f69aa109569. I've been confused with how functional programming differs from procedural programming for a while and want to understand it.
function getOdds2(arr){
return arr.filter(num => num % 2 !== 0)
}
"we simply define the outcome we want to see by using a method called filter, and allow the machine to take care of all the steps in between. This is a more declarative approach."
They say they define the outcome we want to see. How is that any different from procedural programming where you call a function (a sub routine) and get the output you want to see. How is this "declarative approach" any different than just calling a function. The only difference I see between functional and procedural programming is the style.
Procedural programming uses procedures (i.e. calls functions, aka subroutines) and potentially (refers to, and/or changes in place aka "mutates") lots of global variables and/or data structures, i.e. "state".
Functional programming seeks to have all the relevant state in the function's arguments and return values, to minimize if not outright forbid the state external to the functions used (called) in a program.
So, it seeks to have few (or none at all) global variables and data structures, just have functions (subroutines) passing data along until the final one produces the result.
Both are calling functions / subroutines, yes. That's just structured programming, though.
"Pure" functional programming doesn't want its functions to have (and maintain) any internal state (between the calls) either. That way the programming functions / subroutines / procedures become much like mathematical functions, always producing the same output for the same input(s). The operations of such functions become reliable, allowing for the more declarative style of programming. (when it might do something different each time it's called, there's no name we can give it, no concept to call it for).
With functional programming, everything revolves around functions. In the example you gave above, you are defining and executing a function without even knowing it.
You're passing a lambda (anonymous function) to the filter function. With functional programming, that's really the point - defining everything in terms of functions, passing functions as arguments to functions, etc.
So yes, it is about style. It's about ease of expressing your ideas in code and being additionally terse.
Take this for example:
function getOdds(array) {
odds = [];
for(var i = 0; i < array.length; i++) {
if(isOdd(array[i]) array.push(i);
}
}
function isOdd(n) {
return n % 2 != 0;
}
it gets the job done but it's really verbose. Now compare it to:
function getOdds(array) {
array.filter(n => n % 2 != 0)
}
Here you're defining the isOdd function anonymously as a lambda and passing it directly to the filter function. Saves a lot of keystrokes.

What do you call this? Function that sets parameters of other function as fixed

When I took a class on function programming at university a few years back, we learned about this programming pattern, where you have a function that takes X arguments, and then you define another function that only takes X-1 arguments and sets the last one as constant.
Example (python):
createTensor = lambda x,y,z: [[[0 for _ in range(x)] for _ in range(y)] for _ in range(z)]
createMatrix = lambda x,y: createTensor(x,y,1)
createVector = lambda x: createMatrix(x,1)
Would be fun to hear what such a function would be called.
Since the answer was in the comments, I'll just post it as a regular answer:
It's called a partial function application. The function itself would be called a partially applied function.
The concept is related to "currying" (decomposing a function into functions that take only one argument), which I believe is the concept I actually remembered from my classes - and probably the name I had in mind when I posted the question.

javascript fold reduce functional programming

In Javascript there is reduce function which takes function and array, map over the array and return whatever the function return.
For example:
[1, 2, 3].reduce(function(acc, x) {
acc += x
return acc;
}, 0); // 6
In Haskell there is fold which for me do the same:
foldl (+) 0 [1,2,3] -> 6
If i want to create that kind of function as library is it safe to call it fold instead of reduce and is there any difference between the two.
Does both functions the same except the name or there is some difference
I demostrate with different languages because Js doesnt have foldl function.
Thanks
Naming is inconsistent, and depends on the language.
In some contexts like Kotlin, reduce doesn't take an initial value, but fold does. In Haskell, there's foldl and foldl1 to differentiate between the two kinds. In Clojure, the same function reduce has different overloads for taking an initial value, or not taking one.
They're basically describing the same concept, and I've never found any clear difference between the two names.

Can this be considered a pure function (functional programming)?

I've been reading about functional programming and its concepts. It's clear to me that when working in big projects you always need to mix (at some adequate level) multiple paradigms such as OO and functional. In theory, concepts such as function purity are too strict such as
The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices. (https://en.wikipedia.org/wiki/Pure_function)
That said, is this (or can be considered) code a pure function?
const externalVar = 10;
function timesTen(value) {
return externalVar * value;
}
I'm asking this because, in this case, the timesTen function will always return the same value for an input, and anyone can change the value of externalVar as this is a constant. However, this code breaks the rule of accessing external function's scope.
Yes. It is guaranteed to be pure.
The reason is that it only depends on bound and immutable free variables.
However, this code breaks the rule of accessing external function's
scope.
There is nothing in your quote that says you cannot access free variables. It says external input as reading from a file, network, etc not a free variable from a previous scope.
Even Haskell use global function names like foldr and it is a free variable in every function it is used and of course the result is pure.
Remember that functions by name is just variables. parseInt is a variable that points to a function so it would have been hard to make anything at all if every function you should use in another function be passed as parameter.
If you redefine parseInt to something that is not pure or during the duration of your program so that it works differently then no function calling it would be pure.
Function composition and partial evaluation work because they supply free variables. Its an essential method of abstraction in functional programming. eg.
function compose(f2, f1) {
return (...args) => f2(f1(...args));
}
function makeAdder(initialValue) {
return v => v + initialValue;
}
const add11 = compose(makeAdder(10), makeAdder(1));
add11(5); // ==> 16
This is pure. The closure variable / free variable f1, f2, initialValue never changes for the created functions. add11 is a pure function.
Now look at compose again. It looks pure but it can be tainted. If not both functions passed to it were pure the result isn't either.
OO can be purely functional too!
They can easily be combined by not mutating the objects you create.
class FunctionalNumber {
constructor(value) {
this.value = value;
}
add(fn) {
return new FunctionalNumber(this.value + fn.value);
}
sub(fn) {
return new FunctionalNumber(this.value - fn.value);
}
}
This class is purely functional.
In fact you can think of a method call like obj.someMethod(arg1, arg2) as a function call with obj as first argument someFunction(obj, arg1, arg2). It's only syntactic differences and if someFunction mutated obj you would have said it was not pure. This is how it is with someMethod and obj too.
You can make classes that work on large data structures that are functional, which means you never have to copy it before changing when doing a backtracking puzzle solver. A simple example is the pair in Haskell and Lisp. Here is one way to make it in JavaScript:
class Cons {
constructor(car, cdr) {
this.car = car;
this.cdr = cdr;
}
}
const lst = new Cons(1, new Cons(2, new Cons(3, null)));
const lst0 = new Cons(0, lst);
lst0 is lst but with a new element in front. lst0 reuses everything in lst. Everything from lists to binary trees can be made with this and you can make many sequential data structures with immutable binary trees. It's been around since the 50s.
I understand your opinion and totally agree with #Sylwester, but there's a point that is worth mention: with reflection external constant values can be modified and break the pureness of your function. We know that everything in IT can be hacked and we should not considere this over the concepts, but in practice we should have this clear in mind, that in this way functional pureness is unsound.

What is this functional "pattern" called?

I was fooling around with some functional programming when I came across the need for this function, however I don't know what this sort of thing is called in standard nomenclature.
Anyone recognizes it?
function WhatAmIDoing(args...)
return function()
return args
end
end
Edit: generalized the function, it takes a variable amount of arguments ( or perhaps an implicit list) and returns a function that when invoked returns all the args, something like a curry or pickle, but it doesn't seem to be either.
WhatAmIDoing is a higher-order function because it is a function that returns another function.
The thing that it returns is a thunk — a closure created for delayed computation of the actual value. Usually thunks are created to lazily evaluate an expression (and possibly memoize it), but in other cases, a function is simply needed in place of a bare value, as in the case of "constantly 5", which in some languages returns a function that always returns 5.
The latter might apply in the example given, because assuming the language evaluates in applicative-order (i.e. evaluates arguments before calling a function), the function serves no other purpose than to turn the values into a function that returns them.
WhatAmIDoing is really an implementation of the "constantly" function I was describing. But in general, you don't have to return just args in the inner function. You could return "ackermann(args)", which could take a long time, as in...
function WhatAmIDoing2(args...)
return function()
return ackermann(args)
end
end
But WhatAmIDoing2 would return immediately because evaluation of the ackermann function would be suspended in a closure. (Yes, even in a call-by-value language.)
In functional programming a function that takes another function as an argument or returns another function is called a higher-order function.
I would say that XXXX returns a closure of the unnamed function bound on the values of x,y and z.
This wikipedia article may shed some light
Currying is about transforming a function to a chain of functions, each taking only one parameter and returning another such function. So, this example has no relation to currying.
Pickling is a term ususally used to denote some kind of serialization. Maybe for storing a object built from multiple values.
If the aspect interesting to you is that the returned function can access the arguments of the XXXX function, then I would go with Remo.D.
As others have said, it's a higher-order function. As you have "pattern" in your question, I thought I'd add that this feature of functional languages is often modelled using the strategy pattern in languages without higher-order functions.
Something very similar is called constantly in Clojure:
http://github.com/richhickey/clojure/blob/ab6fc90d56bfb3b969ed84058e1b3a4b30faa400/src/clj/clojure/core.clj#L1096
Only the function that constantly returns takes an arbitrary amount of arguments, making it more general (and flexible) than your pattern.
I don't know if this pattern has a name, but would use it in cases where normally functions are expected, but all I care for is that a certain value is returned:
(map (constantly 9) [1 2 3])
=> (9 9 9)
Just wondering, what do you use this for?
A delegate?
Basically you are returning a function?? or the output of a function?
Didn't understand, sorry...

Resources