342 search results for "function"

Showing 1 - 50
  1. 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
  2. Values and Functions

    Anonymous Functions

    Anonymous functions are often passed as arguments to other functions. The identity

    Introduction
  3. Values and Functions

    Types of Functions of Multiple Parameters

    above. Except they are not displayed. Functions having type (string -> string) -> string take a function as a parameter. The function sweet_cat has a

    Introduction
  4. 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
  5. 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
  6. 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
  7. A Tour of OCaml

    Type Parameters and Higher-Order Functions

    ements have the same type of its input. Output list elements have the same type of 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
  8. 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
  9. Values and Functions

    Defining Local Functions

    Although local functions are often defined inside the function's scope, this is not a requirement. The

    Introduction
  10. 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
  11. Higher Order Functions

    Introduction

    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 orig [...] hing_to_do to fn we get a nice little repeat function: We can let repeat call say_hi many times by delaying the

    Introduction
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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: This is true for functions that have the most important argument in the last position (which we call t-last ) and for

    Introduction
  20. Sequences

    Sequences Are Functions

    a mistake like in the first definition of fibs was made. Sequence consumer: partially applied function parameter Sequence producer: partially applied function result Functions working with sequences must be written accordingly. Sequences are

    Data Structures
  21. Higher 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

    Introduction
  22. Values 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:

    Introduction
  23. Monads

    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 Structures
  24. Monads

    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 Structures
  25. A 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 [...] s is not OCaml syntax): Here is an example of a function which creates a list of consecutive integers between two bounds. A recursive

    First Steps
  26. Loops 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

    Introduction
  27. Higher 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

    Introduction
  28. 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
  29. Values 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

    Introduction
  30. OCaml 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

    Resources
  31. Loops 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

    Introduction
  32. Higher 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:

    Introduction
  33. Higher 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

    Introduction
  34. Values 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

    Introduction
  35. Calling 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

    Tutorials
  36. Loops 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

    Introduction
  37. Values 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 ),

    Introduction
  38. A Tour of OCaml

    Polymorphic Functions on Lists

    This function operates not just on lists of integers but on any kind of list. It is a polymorphic function. Its type indicates input of type 'a list where 'a is a type variable standing for any type. Th

    First Steps
  39. Calling 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

    Tutorials
  40. Calling 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

    Tutorials
  41. OCaml Programming Guidelines

    Naming Anonymous Functions

    Justification : Much clearer, in particular if the name given to the function is meaningful. <!-- $MDX skip --> write <!-- [...] e case of an iterator whose argument is a complex function, define the

    Resources
  42. OCaml Programming Guidelines

    Pattern-matching in anonymous functions

    <!-- $MDX skip --> Similarly to match or try , pattern-matching of anonymous functions, starting with function , are indented with respect to the

    Resources
  43. Error Handling

    Safe vs. Unsafe Functions

    The main ways to write such safe error-handling functions are to use either option (next section) or result (following section) values. Although handling errors in data using those types may avoid the issues of error values and exceptions, it requ

    Guides
  44. Error Handling

    Composing Functions Returning Options

    ne 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
  45. Mutability 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

    Introduction
  46. Mutability and Imperative Control Flow

    Good: Functional by Default

    Most existing modules provide an interface meant to be used in a functional way. Some would require the development and mai [...] 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

    Introduction
  47. Lists

    Folds

    Here are some more redefinitions of familiar functions in terms of fold_left or fold_right . Can y [...] he @ operator as its first argument, and so the function has a worse running time than List.concat . You can read more about the time and space effici

    Introduction
  48. Higher Order Functions

    Iterating over Lazy Sequences

    This is almost exactly how Seq.iter is defined in the standard library. This function will try to get the first element of the sequence, and if there is one, run our function fn over it. Then it will repeat over the new sequence ( seq2 ) which starts at the second element

    Introduction
  49. 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
  50. Error Handling

    Using Fun.protect

    ing an exception. Either way, the file descriptor is closed after use. Let's demonstrate with a function that tries reading the first n lines of a tex [...] ad ). If the file has fewer than n lines, the function must throw End_of_file . In any case, the file descriptor must be closed afterwards. Here is a p

    Guides