Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Higher-order function
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Direct support=== ''The examples are not intended to compare and contrast programming languages, but to serve as examples of higher-order function syntax'' In the following examples, the higher-order function {{code|twice}} takes a function, and applies the function to some value twice. If {{code|twice}} has to be applied several times for the same {{code|f}} it preferably should return a function rather than a value. This is in line with the "[[don't repeat yourself]]" principle. ====APL==== {{further information|APL (programming language)}} <syntaxhighlight lang="apl"> twice←{⍺⍺ ⍺⍺ ⍵} plusthree←{⍵+3} g←{plusthree twice ⍵} g 7 13 </syntaxhighlight> Or in a tacit manner: <syntaxhighlight lang="apl"> twice←⍣2 plusthree←+∘3 g←plusthree twice g 7 13 </syntaxhighlight> ====C++==== {{further information|C++}} Using {{code|std::function}} in [[C++11]]: <syntaxhighlight lang="c++"> #include <iostream> #include <functional> auto twice = [](const std::function<int(int)>& f) { return [f](int x) { return f(f(x)); }; }; auto plus_three = [](int i) { return i + 3; }; int main() { auto g = twice(plus_three); std::cout << g(7) << '\n'; // 13 } </syntaxhighlight> Or, with generic lambdas provided by C++14: <syntaxhighlight lang="c++"> #include <iostream> auto twice = [](const auto& f) { return [f](int x) { return f(f(x)); }; }; auto plus_three = [](int i) { return i + 3; }; int main() { auto g = twice(plus_three); std::cout << g(7) << '\n'; // 13 } </syntaxhighlight> ====C#==== {{further information|C Sharp (programming language)}} Using just delegates: <syntaxhighlight lang="csharp"> using System; public class Program { public static void Main(string[] args) { Func<Func<int, int>, Func<int, int>> twice = f => x => f(f(x)); Func<int, int> plusThree = i => i + 3; var g = twice(plusThree); Console.WriteLine(g(7)); // 13 } } </syntaxhighlight> Or equivalently, with static methods: <syntaxhighlight lang="csharp"> using System; public class Program { private static Func<int, int> Twice(Func<int, int> f) { return x => f(f(x)); } private static int PlusThree(int i) => i + 3; public static void Main(string[] args) { var g = Twice(PlusThree); Console.WriteLine(g(7)); // 13 } } </syntaxhighlight> ====Clojure==== {{further information|Clojure}} <syntaxhighlight lang="clojure"> (defn twice [f] (fn [x] (f (f x)))) (defn plus-three [i] (+ i 3)) (def g (twice plus-three)) (println (g 7)) ; 13 </syntaxhighlight> ====ColdFusion Markup Language (CFML)==== {{further information|ColdFusion Markup Language}} <syntaxhighlight lang="cfs"> twice = function(f) { return function(x) { return f(f(x)); }; }; plusThree = function(i) { return i + 3; }; g = twice(plusThree); writeOutput(g(7)); // 13 </syntaxhighlight> ====Common Lisp==== {{further information|Common Lisp}} <syntaxhighlight lang="lisp"> (defun twice (f) (lambda (x) (funcall f (funcall f x)))) (defun plus-three (i) (+ i 3)) (defvar g (twice #'plus-three)) (print (funcall g 7)) </syntaxhighlight> ====D==== {{further information|D (programming language)}} <syntaxhighlight lang="d"> import std.stdio : writeln; alias twice = (f) => (int x) => f(f(x)); alias plusThree = (int i) => i + 3; void main() { auto g = twice(plusThree); writeln(g(7)); // 13 } </syntaxhighlight> ====Dart==== {{further information|Dart (programming language)}} <syntaxhighlight lang="dart"> int Function(int) twice(int Function(int) f) { return (x) { return f(f(x)); }; } int plusThree(int i) { return i + 3; } void main() { final g = twice(plusThree); print(g(7)); // 13 } </syntaxhighlight> ====Elixir==== {{further information|Elixir (programming language)}} In Elixir, you can mix module definitions and [[anonymous function]]s <syntaxhighlight lang="elixir"> defmodule Hof do def twice(f) do fn(x) -> f.(f.(x)) end end end plus_three = fn(i) -> i + 3 end g = Hof.twice(plus_three) IO.puts g.(7) # 13 </syntaxhighlight> Alternatively, we can also compose using pure anonymous functions. <syntaxhighlight lang="elixir"> twice = fn(f) -> fn(x) -> f.(f.(x)) end end plus_three = fn(i) -> i + 3 end g = twice.(plus_three) IO.puts g.(7) # 13 </syntaxhighlight> ====Erlang==== {{further information|Erlang (programming language)}} <syntaxhighlight lang="erlang"> or_else([], _) -> false; or_else([F | Fs], X) -> or_else(Fs, X, F(X)). or_else(Fs, X, false) -> or_else(Fs, X); or_else(Fs, _, {false, Y}) -> or_else(Fs, Y); or_else(_, _, R) -> R. or_else([fun erlang:is_integer/1, fun erlang:is_atom/1, fun erlang:is_list/1], 3.23). </syntaxhighlight> In this Erlang example, the higher-order function {{code|or_else/2}} takes a list of functions ({{code|Fs}}) and argument ({{code|X}}). It evaluates the function {{code|F}} with the argument {{code|X}} as argument. If the function {{code|F}} returns false then the next function in {{code|Fs}} will be evaluated. If the function {{code|F}} returns {{code|{false, Y} }} then the next function in {{code|Fs}} with argument {{code|Y}} will be evaluated. If the function {{code|F}} returns {{code|R}} the higher-order function {{code|or_else/2}} will return {{code|R}}. Note that {{code|X}}, {{code|Y}}, and {{code|R}} can be functions. The example returns {{code|false}}. ====F#==== {{further information|F Sharp (programming language)}} <syntaxhighlight lang="fsharp"> let twice f = f >> f let plus_three = (+) 3 let g = twice plus_three g 7 |> printf "%A" // 13 </syntaxhighlight> ====Go==== {{further information|Go (programming language)}} <syntaxhighlight lang="go"> package main import "fmt" func twice(f func(int) int) func(int) int { return func(x int) int { return f(f(x)) } } func main() { plusThree := func(i int) int { return i + 3 } g := twice(plusThree) fmt.Println(g(7)) // 13 } </syntaxhighlight> Notice a function literal can be defined either with an identifier ({{code|twice}}) or anonymously (assigned to variable {{code|plusThree}}). ====Groovy==== {{further information|Groovy (programming language)}} <syntaxhighlight lang="groovy">def twice = { f, x -> f(f(x)) } def plusThree = { it + 3 } def g = twice.curry(plusThree) println g(7) // 13 </syntaxhighlight> ====Haskell==== {{further information|Haskell}} <syntaxhighlight lang="haskell"> twice :: (Int -> Int) -> (Int -> Int) twice f = f . f plusThree :: Int -> Int plusThree = (+3) main :: IO () main = print (g 7) -- 13 where g = twice plusThree </syntaxhighlight> ====J==== {{further information|J (programming language)}} Explicitly, <syntaxhighlight lang="J"> twice=. adverb : 'u u y' plusthree=. verb : 'y + 3' g=. plusthree twice g 7 13 </syntaxhighlight> or tacitly, <syntaxhighlight lang="J"> twice=. ^:2 plusthree=. +&3 g=. plusthree twice g 7 13 </syntaxhighlight> ====Java (1.8+)==== {{further information|Java (programming language)|Java version history}} Using just functional interfaces: <syntaxhighlight lang="java"> import java.util.function.*; class Main { public static void main(String[] args) { Function<IntUnaryOperator, IntUnaryOperator> twice = f -> f.andThen(f); IntUnaryOperator plusThree = i -> i + 3; var g = twice.apply(plusThree); System.out.println(g.applyAsInt(7)); // 13 } } </syntaxhighlight> Or equivalently, with static methods: <syntaxhighlight lang="java"> import java.util.function.*; class Main { private static IntUnaryOperator twice(IntUnaryOperator f) { return f.andThen(f); } private static int plusThree(int i) { return i + 3; } public static void main(String[] args) { var g = twice(Main::plusThree); System.out.println(g.applyAsInt(7)); // 13 } } </syntaxhighlight> ====JavaScript==== {{further information|JavaScript}} With arrow functions: <syntaxhighlight lang="javascript"> "use strict"; const twice = f => x => f(f(x)); const plusThree = i => i + 3; const g = twice(plusThree); console.log(g(7)); // 13 </syntaxhighlight> Or with classical syntax: <syntaxhighlight lang="javascript"> "use strict"; function twice(f) { return function (x) { return f(f(x)); }; } function plusThree(i) { return i + 3; } const g = twice(plusThree); console.log(g(7)); // 13 </syntaxhighlight> ====Julia==== {{further information|Julia (programming language)}} <syntaxhighlight lang="jlcon"> julia> function twice(f) function result(x) return f(f(x)) end return result end twice (generic function with 1 method) julia> plusthree(i) = i + 3 plusthree (generic function with 1 method) julia> g = twice(plusthree) (::var"#result#3"{typeof(plusthree)}) (generic function with 1 method) julia> g(7) 13 </syntaxhighlight> ====Kotlin==== {{further information|Kotlin (programming language)}} <syntaxhighlight lang="kotlin"> fun twice(f: (Int) -> Int): (Int) -> Int { return { f(f(it)) } } fun plusThree(i: Int) = i + 3 fun main() { val g = twice(::plusThree) println(g(7)) // 13 } </syntaxhighlight> ==== Lua ==== {{further information|Lua (programming language)}} <syntaxhighlight lang="lua"> function twice(f) return function (x) return f(f(x)) end end function plusThree(i) return i + 3 end local g = twice(plusThree) print(g(7)) -- 13 </syntaxhighlight> ==== MATLAB ==== {{further information|MATLAB}} <syntaxhighlight lang="matlab"> function result = twice(f) result = @(x) f(f(x)); end plusthree = @(i) i + 3; g = twice(plusthree) disp(g(7)); % 13 </syntaxhighlight> ==== OCaml ==== {{further information|OCaml}} <syntaxhighlight lang="ocaml" start="1"> let twice f x = f (f x) let plus_three = (+) 3 let () = let g = twice plus_three in print_int (g 7); (* 13 *) print_newline () </syntaxhighlight> ====PHP==== {{further information|PHP}} <syntaxhighlight lang="php"> <?php declare(strict_types=1); function twice(callable $f): Closure { return function (int $x) use ($f): int { return $f($f($x)); }; } function plusThree(int $i): int { return $i + 3; } $g = twice('plusThree'); echo $g(7), "\n"; // 13 </syntaxhighlight> or with all functions in variables: <syntaxhighlight lang="php"> <?php declare(strict_types=1); $twice = fn(callable $f): Closure => fn(int $x): int => $f($f($x)); $plusThree = fn(int $i): int => $i + 3; $g = $twice($plusThree); echo $g(7), "\n"; // 13 </syntaxhighlight> Note that arrow functions implicitly capture any variables that come from the parent scope,<ref>{{Cite web|title=PHP: Arrow Functions - Manual|url=https://www.php.net/manual/en/functions.arrow.php|access-date=2021-03-01|website=www.php.net}}</ref> whereas anonymous functions require the {{code|use}} keyword to do the same. ====Perl==== {{further information|Perl}} <syntaxhighlight lang="perl"> use strict; use warnings; sub twice { my ($f) = @_; sub { $f->($f->(@_)); }; } sub plusThree { my ($i) = @_; $i + 3; } my $g = twice(\&plusThree); print $g->(7), "\n"; # 13 </syntaxhighlight> or with all functions in variables: <syntaxhighlight lang="perl"> use strict; use warnings; my $twice = sub { my ($f) = @_; sub { $f->($f->(@_)); }; }; my $plusThree = sub { my ($i) = @_; $i + 3; }; my $g = $twice->($plusThree); print $g->(7), "\n"; # 13 </syntaxhighlight> ====Python==== {{further information|Python (programming language)}} <syntaxhighlight lang="pycon"> >>> def twice(f): ... def result(x): ... return f(f(x)) ... return result >>> plus_three = lambda i: i + 3 >>> g = twice(plus_three) >>> g(7) 13 </syntaxhighlight> Python decorator syntax is often used to replace a function with the result of passing that function through a higher-order function. E.g., the function {{code|g}} could be implemented equivalently: <syntaxhighlight lang="pycon"> >>> @twice ... def g(i): ... return i + 3 >>> g(7) 13 </syntaxhighlight> ====R==== {{further information|R (programming language)}} <syntaxhighlight lang="R"> twice <- \(f) \(x) f(f(x)) plusThree <- function(i) i + 3 g <- twice(plusThree) > g(7) [1] 13 </syntaxhighlight> ====Raku==== {{further information|Raku (programming language)}} <syntaxhighlight lang="perl6"> sub twice(Callable:D $f) { return sub { $f($f($^x)) }; } sub plusThree(Int:D $i) { return $i + 3; } my $g = twice(&plusThree); say $g(7); # 13 </syntaxhighlight> In Raku, all code objects are closures and therefore can reference inner "lexical" variables from an outer scope because the lexical variable is "closed" inside of the function. Raku also supports "pointy block" syntax for lambda expressions which can be assigned to a variable or invoked anonymously. ====Ruby==== {{further information|Ruby (programming language)}} <syntaxhighlight lang="ruby"> def twice(f) ->(x) { f.call(f.call(x)) } end plus_three = ->(i) { i + 3 } g = twice(plus_three) puts g.call(7) # 13 </syntaxhighlight> ====Rust==== {{further information|Rust (programming language)}} <syntaxhighlight lang="rust"> fn twice(f: impl Fn(i32) -> i32) -> impl Fn(i32) -> i32 { move |x| f(f(x)) } fn plus_three(i: i32) -> i32 { i + 3 } fn main() { let g = twice(plus_three); println!("{}", g(7)) // 13 } </syntaxhighlight> ====Scala==== {{further information|Scala (programming language)}} <syntaxhighlight lang="scala"> object Main { def twice(f: Int => Int): Int => Int = f compose f def plusThree(i: Int): Int = i + 3 def main(args: Array[String]): Unit = { val g = twice(plusThree) print(g(7)) // 13 } } </syntaxhighlight> ====Scheme==== {{further information|Scheme (programming language)}} <syntaxhighlight lang="scheme"> (define (compose f g) (lambda (x) (f (g x)))) (define (twice f) (compose f f)) (define (plus-three i) (+ i 3)) (define g (twice plus-three)) (display (g 7)) ; 13 (display "\n") </syntaxhighlight> ====Swift==== {{further information|Swift (programming language)}} <syntaxhighlight lang="swift"> func twice(_ f: @escaping (Int) -> Int) -> (Int) -> Int { return { f(f($0)) } } let plusThree = { $0 + 3 } let g = twice(plusThree) print(g(7)) // 13 </syntaxhighlight> ====Tcl==== {{further information|Tcl}} <syntaxhighlight lang="tcl"> set twice {{f x} {apply $f [apply $f $x]}} set plusThree {{i} {return [expr $i + 3]}} # result: 13 puts [apply $twice $plusThree 7] </syntaxhighlight> Tcl uses apply command to apply an anonymous function (since 8.6). ====XACML==== {{further information|XACML}} The XACML standard defines higher-order functions in the standard to apply a function to multiple values of attribute bags. <syntaxhighlight lang="xquery"> rule allowEntry{ permit condition anyOfAny(function[stringEqual], citizenships, allowedCitizenships) } </syntaxhighlight> The list of higher-order functions in XACML can be found [[XACML#Higher order functions|here]]. ====XQuery==== {{further information|XQuery}} <syntaxhighlight lang="xquery"> declare function local:twice($f, $x) { $f($f($x)) }; declare function local:plusthree($i) { $i + 3 }; local:twice(local:plusthree#1, 7) (: 13 :) </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)