Thursday, August 17, 2017

Julia - Language - Functions - Single Expression Functions

These functions can be written in a single expression and mimic the way we solve maths functions on a piece of paper. Consider the popular function, f(x) = x*x = x^2


$ julia
               _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.6.0 (2017-06-19 13:05 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-pc-linux-gnu

julia> f(x) = x^2
f (generic function with 1 method)

julia> f(2)
4


Let us see all the methods which we can pass to our square function.

julia> methods(f)
# 1 method for generic function "f":
f(x) in Main at REPL[1]:1

julia> 

We can see that, single expression function is very convenient. It is a shorthand and almost a mathematical syntax. A single expression function is a generic function with no name.

No comments:

Post a Comment