Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Niidae Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
OCaml
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
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!
===Summing a list of integers=== Lists are one of the fundamental datatypes in OCaml. The following code example defines a [[Recursion (computer science)|recursive]] function ''sum'' that accepts one argument, ''integers'', which is supposed to be a list of integers. Note the keyword <code>rec</code> which denotes that the function is recursive. The function recursively iterates over the given list of integers and provides a sum of the elements. The ''match'' statement has similarities to [[C (programming language)|C]]'s [[Switch statement|switch]] element, though it is far more general. <syntaxhighlight lang="ocaml"> let rec sum integers = (* Keyword rec means 'recursive'. *) match integers with | [] -> 0 (* Yield 0 if integers is the empty list []. *) | first :: rest -> first + sum rest;; (* Recursive call if integers is a non- empty list; first is the first element of the list, and rest is a list of the rest of the elements, possibly []. *) </syntaxhighlight> <syntaxhighlight lang="OCaml"> # sum [1;2;3;4;5];; - : int = 15 </syntaxhighlight> Another way is to use standard [[fold function]] that works with lists. <syntaxhighlight lang="ocaml"> let sum integers = List.fold_left (fun accumulator x -> accumulator + x) 0 integers;; </syntaxhighlight> <syntaxhighlight lang="OCaml"> # sum [1;2;3;4;5];; - : int = 15 </syntaxhighlight> Since the [[anonymous function]] is simply the application of the + operator, this can be shortened to: <syntaxhighlight lang="ocaml"> let sum integers = List.fold_left (+) 0 integers </syntaxhighlight> Furthermore, one can omit the list argument by making use of a [[partial application]]: <syntaxhighlight lang="OCaml"> let sum = List.fold_left (+) 0 </syntaxhighlight>
Summary:
Please note that all contributions to Niidae Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Encyclopedia:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
OCaml
(section)
Add topic