379 search results for "function"
-
Values and Functions
Functions With Side Effects
This illustrates the relationship between functions that have side effects and the unit type. The [...] he unit type is used. Since the purpose of the function is only to produce an effect, it has no meaningful data to return; it returns the () value. Cons
Introduction -
Values and Functions
Recursive Functions
Note : Notice that the fib_loop function has three parameters m n i but when defining f [...] er job: Note : List.init is a standard library function that allows you to create a list by applying a given
Introduction -
Values and Functions
Anonymous Functions
Anonymous functions are often passed as arguments to other functions. The identity
Introduction -
Values and Functions
Types of Functions of Multiple Parameters
The type arrow operator associates to the right . Function types without parentheses should be treated as if [...] s declared above. Except they are not displayed. Functions having type (string -> string) -> string take a
Introduction -
Basic Data Types and Pattern Matching
Functions
(int -> int) -> int : This function takes a function of type int -> int as a parameter and returns an int as the result. int -> (int -> int) : This
Introduction -
Values and Functions
What Makes Functions Different From Other Values
<!-- - Pattern matching does not allow inspecting a function. Catch-all patterns can match against a function, but it is useless. ```ocaml # match Fun.id with _ -> ();; - : unit = () ``` --> <!-- It may seem
Introduction -
Values and Functions
Applying Functions
There are two alternative ways to apply functions. Labelled and optional parameters are detailed in the Labelled Arguments tutorial. Some functions, such as String.starts_with have labelled parameters. Labels are useful when a
Introduction -
Values and Functions
Anonymous Functions with Multiple Parameters
ntactic sugar . The way sour_cat is written corresponds more explicitly to the behaviour of both functions. The name sour_cat is bound to an anonymous function having parameter x and returning an anonymous
Introduction -
Values and Functions
Function as Values
<!-- For now, let's put aside those definitions and instead start playing with functions. Their meaning will arise from experience. Once [...] he community. This is a big takeaway. We believe functional programming (_ergo_ OCaml) is best understood by practising it rather than reading about it. Just
Introduction -
Profiling
Partially Applied Functions and Closures
t be evaluated for each element of the array, and that isn't as fast as inlining the closure as a function (if this optimisation were even possible). Howe [...] into a loop. The actual call to the Array.map function is quite difficult to understand, but the main points for our examination of OCaml is that the
Guides -
A Tour of OCaml
Polymorphism and Higher-Order Functions
ements have the same type as its input. Output list elements have the same type as its output. The function List.map can be applied on any kind of list. He [...] . This is known as polymorphism . The List.map function is polymorphic, meaning it has two implicit type variables : 'a and 'b (pronounced “alpha”
First Steps -
Higher Order Functions
Introduction
Here's some other examples from the real world: This is the power of Higher-Order Functions . They empower you to create complex behaviors from simpler functions. And we can use repeat to recreate our original say_many_hi , or to repeat any work any numb
Introduction -
Values and Functions
Defining Local Functions
Although local functions are often defined inside the function's scope, this is not a requirement. The
Introduction -
Values and Functions
Tuples as Function Parameters
In many imperative languages, the spicy_cat ("hello", "world") syntax reads as a function call with two arguments; but in OCaml, it denotes applying the function spicy_cat to a tuple containing "hello" and "world" . It looks like two arguments have been p
Introduction -
Memoization
Memoization Using Higher-order Functions
Now we can slightly rewrite the original fib function above using this general memoization technique: For recursive functions, however, the recursive call structure needs to be modified. This can be abstracted out independ
Data Structures -
Values and Functions
Currying and Uncurrying
lication No parentheses or commas No pattern matching over a tuple takes place In practice, curried functions are the default because: <!-- Currying and uncurrying can be understood as operations acting on functions the same way addition and subtraction are operations acting on numbers. --> However, it is also
Introduction -
Values and Functions
Defining Global Functions
The former explicitly binds the anonymous function to a name. The latter uses a more compact syntax [...] w symbol. The expression, which happens to be a function, is turned into value and bound to a name. Here is another way to do the same thing: You can globa
Introduction -
Lists
Higher Order Functions on Lists
Notice the type of the function f in parentheses as part of the whole type. This map function, given a
Introduction -
A Tour of OCaml
Functions
Some functions, such as String.ends_with have labelled parameters. Labels are useful when a function has several parameters of the same type; naming arguments allows to guess their purpose. Above, ~s
First Steps -
Higher Order Functions
Async code
<!-- Comment let f () = 42 let f () = g 42 One possible issue with the repeat function used in the intro comes from the fact it is used [...] d deferring evaluation of a side effect producing function in order to repeat it. On one hand, it is good because it feels more real life, on the other hand
Introduction -
Debugging
Polymorphic Functions
For our sorting routine, a single type constraint on the argument of the exchange function warranties a monomorphic typing, that allows a proper trace of function calls: A simple way to overcome this problem is to define a monomorphic version of the faulty
Guides -
Higher Order Functions
Higher Order Functions
Pipelines, Composition, and Chaining
hen it comes to usability. Let's revisit our example above using labeled argument versions of those functions: Note : The "t" in " t-first " and " t-last " [...] " and " target argument last ". This is true for functions that have the most important argument in the last position (which we call t-last ) and for
IntroductionA Tour of OCaml
Defining a Higher-Order Function
It is possible to pass a function as argument to another function.
First StepsHigher Order Functions
Currying
But we can also curry our reveal function to take 2 arguments! If we wanted to use reve [...] ple this list of names and an uncurried revealing function: Currying can be very useful when you're dealing with lists (which we do a lot in OCaml) and when
IntroductionValues and Functions
Defining Functions with Multiple Parameters
To define a function with multiple parameters, each must be listed between the name of the function (right after the let keyword) and the equal sign, separated by space:
IntroductionMonads
The Maybe Monad
ow to read the bind operator) is easier to read and easier to maintain. In practice the return function here is quite trivial and not really necessary. [...] your eye as Using just the return and >>= functions, we could re-implement the arithmetic operations from above: All those type annotations are i
Data StructuresMonads
Example: The Writer Monad
ersion of it that uses >>= . But if you were developing a much larger code base (i.e., with more functions involving paired strings than just loggable ), [...] catenation. Here's that idea expressed as its own function: This
Data StructuresLoops and Recursions
Mutually Recursive Functions
m C) in OCaml, but there is a special syntax for defining a set of two or more mutually recursive functions, like odd and even : The only problem is... [...] doesn't compile. In order to compile the even function, we need to already have the definition of odd , and to compile odd , we need the definition of
IntroductionLists
Functions on Lists
he pattern _ :: t the head of the list is not inspected, so its type cannot be relevant. Such a function is called polymorphic. Here is another polymorphic function, our own version of the @ operator for appending: This
IntroductionMutability and Imperative Control Flow
Example: get_char Function
to avoid an Unbound module error . We read characters from standard input using the input_char function from the OCaml standard library. Read and record [...] minal attributes (similar to assign ) We use two functions from the Unix module to read and update attributes of the terminal associated with standard inpu
IntroductionA Tour of OCaml
Functions with Multiple Parameters and Partial Application
The function cat_hi , which resulted from the partial applica [...] ion of cat , behaves as follows: This returns a function that expects a single string, here the b from the definition of cat . This is called a partial
First StepsA Tour of OCaml
Recursive Functions
n takes place between the two last steps. As indicated by its type int -> int -> int list , the function range takes two integers as arguments and retur [...] is not OCaml syntax): Here is an example of a function which creates a list of consecutive integers between two bounds. A recursive
First StepsHigher Order Functions
Uncurrying
But we can also uncurry our greet function to operate over the entire tuple! If we wanted [...] lements, we'd need to split the tuple, and call a function: Take for example this list of tuples of names and favorite emojis: Uncurrying can be very usef
IntroductionValues and Functions
Conclusion
<!-- One may wonder: > Why is function-as-values the key concept of functional programming? The answer to this question goes beyond the scope of this tutorial. This comes from
IntroductionHigher Order Functions
Currying and Uncurrying
Before we get to some examples, let's define some helper functions that will help us curry and uncurry functions. A curried add
IntroductionOCaml Programming Guidelines
Imperative and Functional Versions of list_length
f complexity. The imperative version uses a constant amount of stack room to execute, whereas the functional version needs to store return addresses of su [...] etrieve a constant space requirement to run the functional program, you simply must write a
ResourcesLoops and Recursions
Tail Recursion
One thing is that recursive functions have a dangerous trap for inexperienced programmers. Your function can appear to work for small inputs (during testing), but then fail catastrophically in the field
IntroductionValues and Functions
Introduction
ts by example. You are encouraged to modify the examples to gain a better understanding. In OCaml, functions are treated as values, so you can use functions as arguments to
IntroductionHigher Order Functions
Common Higher-Order Functions
ing) Sorting Binding (or flat mapping) In the wild, there's certain patterns that repeat over and over again. It's useful to be familiar with them because they are part of the common vocabulary of a functional programmer. Some of them are:
IntroductionCalling C Libraries
Wrapping Calls to C Libraries
ound as an opaque "thing" ( obj ) through our OCaml code, and hopefully pass it back later to a C function which can unwrap it and retrieve the same GtkO [...] stly copied from lablgtk. There are two related functions, called wrap and unwrap and as you might possibly have guessed, they wrap and unwrap GtkObj
TutorialsLoops and Recursions
Approach 3
The use of recursion to build up trees: <!-- $MDX skip --> Compare this to our previous range function. The pattern of recursion is exactly the same: [...] mplex patterns of recursion found in real-world functional programs. The two important lessons to take away from this are: What do we do when loop re
IntroductionValues and Functions
Closures
Inside the max_42 function, the environment contains an additional binding b [...] the value 42. Partially applying arguments to a function also creates a new closure. However, all future expressions will use the new value of j ( 7 ),
IntroductionMutability and Imperative Control Flow
Good: Function-Encapsulated Mutability
The function sum is written in an imperative style, using mu [...] a fully encapsulated implementation choice. This function is safe to use; no problems are to be expected. Here is a
IntroductionMutability and Imperative Control Flow
Good: Functional by Default
Most existing modules provide an interface meant to be used in a functional way. Some require the development and maintenan [...] to only program in an imperative style. Not using functional programming idioms at all would result in non-idiomatic OCaml code. By default, OCaml programs s
IntroductionSequences
Sequence Consumers: Partially Applied Functions as Parameters
A consumer is a function that processes a sequence, consuming its elem [...] ents. Consumers should be written as higher-order functions that take a
Data StructuresCalling C Libraries
MiniGtk
finally get to the label class, which is derived directly from misc : It's that tricky may function in action. If the user gave an alignment arg [...] e initializer uses these: We start with a helper function called may : ('a -> unit) -> 'a option -> unit which invokes its first argument on the content
TutorialsCalling Fortran Libraries
Step 1: Compile the Fortran Routine
e actually arrays. Failure to pass an array will cause a segmentation violation since the gtd6_ function is using them as arrays (yet another reason OCa [...] e so the corresponding C prototype for our gtd6 function is This shows that the
TutorialsError Handling
Safe vs. Unsafe Functions
The main ways to write such safe error-handling functions are to use either option (next section) or r [...] boilerplate code and comes with a runtime cost. Function raising exceptions: Unsafe
GuidesError Handling
Composing Functions Returning Options
argument if applied to None . In order to combine option values with other values, conversion functions are needed. Here are the functions provided by the option module to extract the data contained in an option: The
Guides