PE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> zwarte horloges voor mannen langref.org - ocaml and erlangAccesorios : Reino Unido Moncler Outlet - Moncler Oficial UK Venta Online/title>html; charset=utf-8" />keywords" content="Accesorios Moncler Moncler Abrigos Moncler 2015-2016 Chaquetas Moncler Chalecos Moncler Outlet Reino Unido , Moncler Outlet , Moncler Reino Unido Venta Accesorios" />description" content=" />imagetoolbar" content="no" />canonical" href="http://www.monclermen.biz/es/accesorios-c-13.html" />stylesheet" type="text/css" href="http:/www.monclermen.biz/es/includes/templates/polo/css/style_imagehover.css" />"stylesheet"type="text/css"href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet.css"/>css" href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet_css_buttons.css" />stylesheet" type="text/css" media="print" href="http:/www.monclermen.biz/es/includes/templates/polo/css/print_stylesheet.css" />"currency"onchange="this.form.submit();">"USD

langref.org - ocaml and erlangAccesorios : Reino Unido Moncler Outlet - Moncler Oficial UK Venta Online/title>html; charset=utf-8" />keywords" content="Accesorios Moncler Moncler Abrigos Moncler 2015-2016 Chaquetas Moncler Chalecos Moncler Outlet Reino Unido , Moncler Outlet , Moncler Reino Unido Venta Accesorios" />description" content=" />imagetoolbar" content="no" />canonical" href="http://www.monclermen.biz/es/accesorios-c-13.html" />stylesheet" type="text/css" href="http:/www.monclermen.biz/es/includes/templates/polo/css/style_imagehover.css" />"stylesheet"type="text/css"href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet.css"/>css" href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet_css_buttons.css" />stylesheet" type="text/css" media="print" href="http:/www.monclermen.biz/es/includes/templates/polo/css/print_stylesheet.css" />"currency"onchange="this.form.submit();">"USD zwarte horloges voor mannen

All Problems Strings Printing

Output a string to the console

Write the string "Hello World!" to STDOUT ocaml print_string "Hello world!\n";;print_endline "Hello world!";;Printf.printf "Hello world!\n";; erlang io:format("Hello, World!~n").

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith" . The script variable for first name $_REQUEST ['firstname'] never gets beyond the "Ron" value because of the ampersand in the data. I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname=" Ronxxnbsp;xxamp;xxnbsp;Jean "&lname=SMITH" . (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.) Of course this fails for the same reasons. What is a better approach? ocaml let query = Netencoding.Url.mk_url_encoded_parameters [ "mode", "view"; "fname", "Ron & Jean"; "lname", "Smith"; ] let url = "http://myserver.com/custinfo/edit.php?" ^ query erlang % encode ampersand in your string using %XX where XX is hex code for ampersand % optionally encode spaces for completeness sake to keep URL solid URL = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20%26%20Jean&lname=Smith", {_, Query} = string:tokens(URL, "?"), KeyValuePairs = string:tokens(Query, "&"),...

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> " Expected output: > The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t > he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox > jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui > ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy > dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o > ver the lazy dog. The quick brown fox jumps over the lazy dog. ocaml let wrapper margin = let cur = ref 0 in fun word -> let len = String.length word in let beginning_of_line () = Printf.printf "> %s" word; cur := len + 2 in if !cur = 0 then beginning_of_line () else begin cur := !cur + 1 + len; if !cur <= margin then Printf.printf " %s" word else begin print_newline (); beginning_of_line () end end let wrap_string wrapper s = let len = String.length s in let rec aux_out i = if i < len then match s.[i] with | ' ' | '\t' | '\n' -> aux_out (i+1) | _ -> aux_in i (i+1) and aux_in i0 i = if i >= len then wrapper (String.sub s i0 (len - i0)) else match s.[i] with | ' ' | '\t' | '\n' -> wrapper (String.sub s i0 (i - i0)); aux_out (i+1) | _ -> aux_in i0 (i+1) in aux_out 0 let () = let base_string = "The quick brown fox jumps over the lazy dog. " in let w = wrapper 78 in for i = 1 to 10 do wrap_string w base_string done; print_newline () erlang wrapper(String, Times, Length) -> StrList = lists:reverse(formatter(string:copies(String, Times), Length, [])), lists:foreach(fun(Str) -> io:format("~p~n", [Str]) end, StrList). formatter([], _Length, Acc) -> Acc; formatter(String, Length, Acc) when length(String) > Length - 1-> {Head, Tail} = lists:split(Length - 1, String), formatter(string:strip(Tail), Length, [[$>, $ | Head] | Acc]); formatter(String, Length, Acc) -> formatter([], Length, [[$>, $ | String] | Acc]). Declaration

Define a string containing special characters

Define the literal string "\#{'}${"}/" ocaml "\\#{'}${\"}/" erlang Special = "\\#{'}\${\"}/",

Define a multiline string

Define the string: "This Is A Multiline String" ocaml "This\nIs\nA\nMultiline\nString""This Is A Multiline String" erlang Text = "This\nIs\nA\nMultiline\nString",

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7" ocaml Printf.printf "%d+%d=%d" a b (a+b);;Printf.printf "%d+%d=%d" a b (a+b);; erlang A = 3, B = 4, io:format("~B+~B=~B~n", [A, B, (A+B)]). Manipulation

Reverse the characters in a string

Given the string "reverse me" , produce the string "em esrever" ocaml let reverse str = let len = String.length str in let res = String.create len in for i = 0 to pred len do let j = pred len - i in res.[i] <- str.[j] done; (res)let rev_char str = let l = Str.split (Str.regexp "") str in List.fold_left (fun a b -> b ^ a) "" l ;; erlang Reversed = lists:reverse("reverse me"),Reversed = revchars("reverse me"),

Reverse the words in a string

Given the string "This is a end, my only friend!" , produce the string "friend! only my end, the is This" ocaml let rev_words str = let l = Str.split (Str.regexp " ") str in String.concat " " (List.rev l) ;; erlang Reversed = string:join(lists:reverse(string:tokens("This is the end, my only friend!", " ")), " "),

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> " , yielding this result: > The quick brown fox jumps over the lazy dog. The quick brown fox jumps > over the lazy dog. The quick brown fox jumps over the lazy dog. The > quick brown fox jumps over the lazy dog. The quick brown fox jumps > over the lazy dog. The quick brown fox jumps over the lazy dog. The > quick brown fox jumps over the lazy dog. The quick brown fox jumps > over the lazy dog. The quick brown fox jumps over the lazy dog. The > quick brown fox jumps over the lazy dog. ocaml (* ocamlbuild -no-hygiene textwrap.native && ./textwrap.native *) let wrap s prefix width = let width = width - (String.length prefix) in let len = String.length s in let rec loop start = if start >= len then [] else let stop = min (len - start) width in let sub = String.sub s start stop in (prefix ^ sub) :: loop (start+stop) in loop 0 in let wrap_and_print s prefix width = List.iter print_endline (wrap s prefix width) in let s = ref "" in for i = 1 to 10 do s := !s ^ "The quick brown fox jumps over the lazy dog. " done; wrap_and_print !s "> " 78 erlang TextWrap = textwrap(string:copies(Input, 10), 73 - length(Prefix)), lists:foreach(fun (Line) -> io:format("~s~n", [string:concat(Prefix, Line)]) end, string:tokens(TextWrap, "\n")).

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello" . ocaml let left_pos s len = let rec aux i = if i >= len then None else match s.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (succ i) | _ -> Some i in aux 0 let right_pos s len = let rec aux i = if i < 0 then None else match s.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (pred i) | _ -> Some i in aux (pred len) let trim s = let len = String.length s in match left_pos s len, right_pos s len with | Some i, Some j -> String.sub s i (j - i + 1) | None, None -> "" | _ -> assert false let () = let res = trim " hello " in print_endline resString.trim " hello " erlang Trimmed = string:strip(S),

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string. For example: String is: Hello World #123 ROT13 returns: Uryyb Jbeyq #123 ROT47 returns: w6==@ (@C=5 R`ab ocaml let rot_char13 c = match c with | 'A'..'M' | 'a'..'m' -> Char.chr ((Char.code c) + 13) | 'N'..'Z' | 'n'..'z' -> Char.chr ((Char.code c) - 13) | _ -> c let rot_char47 c = match c with | '!'..'N' -> Char.chr ((Char.code c) + 47) | 'O'..'~' -> Char.chr ((Char.code c) - 47) | _ -> c let rot f str = let len = String.length str in let res = String.create len in for i = 0 to pred len do res.[i] <- f str.[i] done; (res) let rot13 = rot rot_char13 let rot47 = rot rot_char47 erlang rot13(Str) -> lists:map(fun(A) -> if A >= $A, A =< $Z -> ((A - $A + 13) rem 26) + $A; A >= $a, A =< $z -> ((A - $a + 13) rem 26) + $a; true -> A end end, Str). rot47(Str) -> lists:map(fun(A) -> if A >= $!, A =< $~ -> ((A - $! + 47) rem 94) + $!; true -> A end end, Str). Case

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY" ocaml String.uppercase "Space Monkey";; erlang io:format("~s~n", [string:to_upper("Space Monkey")]).

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated" ocaml String.lowercase "Caps ARE overRated";; erlang io:format("~s~n", [string:to_lower("Caps ARE overRated")]).

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel" ocaml let capitalize_words str = let len = String.length str in let res = String.copy str in let rec aux i do_up = if i >= len then res else match str.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (succ i) true | _ -> res.[i] <- (if do_up then Char.uppercase else Char.lowercase) str.[i]; aux (succ i) false in aux 0 true let () = print_endline (capitalize_words "man OF stEEL")let capitalize_words str = let capitalize_word w = String.capitalize (String.lowercase w) in let l = Str.split (Str.regexp " ") str in String.concat " " (List.map (capitalize_word) l) ;; let () = print_endline (capitalize_words "man OF stEEL");; erlang Caps = string:join(lists:map(fun(S) -> to_caps(S) end, string:tokens("man OF stEEL", " ")), " "), Numbers Mathematical

Find the distance between two points

ocaml type point = { x:float; y:float };; let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);; erlang Distance = distance({point, 34, 78}, {point, 67, -45}), io:format("~.2f~n", [Distance]).Distance = distance(point:new(34, 78), point:new(67, -45)), io:format("~.2f~n", [Distance]). Output

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042 ocaml Printf.printf "%08d" 42;;let s = Printf.sprintf "%08d" 42 in print_string s;; erlang Formatted = io_lib:format("~8..0B", [42]),io:format("~8..0B~n", [42]).

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  " ocaml Printf.printf "%-6i" 1024;; erlang Formatted = io_lib:format("~-6B", [1024]),io:format("~-6B~n", [1024]).

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88 ocaml Printf.printf "%4.2f" (7. /. 8.);;let s = Printf.sprintf "%4.2f" (7. /. 8.) in print_string s;; erlang Formatted = io_lib:format("~.2f", [7/8]),io:format("~.2f~n", [7/8]).

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73" ocaml Printf.printf "%10d" 73;; erlang Formatted = io_lib:format("~10B", [73]),io:format("~10B~n", [73]). Random

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive ocaml Random.self_init ();; let a = 100 and b = 200 in Random.int ( b - a + 1 ) + a;; erlang RandomInt = gen_rand_integer(100, 200),99 + rand:uniform(101).

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values. ocaml let random_stream seed = Random.init seed; let state = ref (Random.get_state ()) in Stream.from (fun x -> Random.set_state !state; let res = Random.float 1. in state := Random.get_state (); Some res);; Stream.npeek 5 (random_stream 1);; Stream.npeek 5 (random_stream 1);; erlang setRNG(RNGState), io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]), setRNG(RNGState), io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]). Regex Matching

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/ ocaml if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0 then print_string "ok";; erlang String = "Hello", Regexp = "[A-Z][a-z]+", is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).case re:run("Hello", "[A-Z][a-z]+") of {match, _} -> ok end.

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/ ocaml #load "str.cma" ;; let s = "one two three" in if Str.string_match (Str.regexp "one \\(.*\\) three") s 0 then print_string (Str.matched_group 1 s) erlang case re:run("one two three", "one (.*) three", [{capture, [1], list}]) of {match, Res} -> hd(Res) end. Searching

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/ ocaml #load "str.cma" ;; let re = Str.regexp "[0-9]+" in try let _ = Str.search_forward re "abc 123 @#$" 0 in print_string "ok" with _ -> () erlang % Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\d' not supported String = "abc 123 @#$", Regexp = "[0-9]+", is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).case re:run("abc 123 @#$", "\\d+") of {match, _} -> ok end.

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/ ocaml let result = let str = "(fish):1 sausage (cow):3 tree (boat):4" in let ms = Pcre.exec_all ~pat:"\\((\\w+)\\):(\\d+)" str in Array.to_list ( Array.map (fun m -> let s = Pcre.get_substrings m in Printf.sprintf "%s%s" s.(1) s.(2); ) ms ) erlang solve(S) -> R = "\\((\\w+?)\\):(\\d+)", {match, M} = re:run(S,R, [global, {capture, all_but_first, list}]), [ A++N || [A, N] <- M]. Replacing

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*" ocaml let replaced = Str.replace_first (Str.regexp "e") "*" "Red Green Blue" in print_endline replaced ;; erlang {ok, Replaced, _} = regexp:sub("Red Green Blue", "e", "*"),re:replace("Red Green Blue", "e", "*", [{return, list}]).

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X" ocaml let s = "She sells sea shells" in Str.global_replace (Str.regexp "se[^ \\t\\n]*") "X" s erlang % Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\w' not supported {ok, Replaced, _} = regexp:gsub("She sells sea shells", "se[A-Za-z0-9_]+", "X"),re:replace("She sells sea shells", "se\\w+", "X", [global, {return, list}]).

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/ . ocaml let s = "The {Quick} Brown {Fox}" in let r = Str.regexp "{\\([^ \\t\\n]*\\)}" in Str.global_substitute r (fun m -> string_rev (Str.matched_group 1 m)) s erlang % Erlang regular expressions lack both group capture and backreferences, thus this problem is not directly % solvable. Presented solution is close, but not on-spec String = "The {Quick} Brown {Fox}", {match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"), NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList), Lists < tkmakvod. billige falske ure online/b> Declaration

Define an empty list

Assign the variable "list" to a list with no elements ocaml let list = [];; erlang List = [],

Define a static list

Define the list [One, Two, Three, Four, Five] ocaml let list = [ "One"; "Two"; "Three"; "Four"; "Five" ];; erlang List = [one, two, three, four, five],List = ['One', 'Two', 'Three', 'Four', 'Five'], Output

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot" ocaml let () = let lst = ["Apple"; "Banana"; "Carrot"] in let str = String.concat ", " lst in print_endline str erlang Result = string:join(Fruit, ", "),Result = lists:foldl(fun (E, Acc) -> Acc ++ ", " ++ E end, hd(Fruit), tl(Fruit)),Result = lists:flatten([ hd(Fruit) | [ ", " ++ X || X <- tl(Fruit)]]).

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples: join( [Apple, Banana, Carrot] ) = "Apple, Banana, and Carrot" join( [One, Two] ) = "One and Two" join( [Lonely] ) = "Lonely" join( [] ) = "" ocaml let join list = let rec join' list acc = match list with | [] -> "" | [single] -> single | one::[two] -> if acc = "" then one ^ " and " ^ two else acc ^ one ^ ", and " ^ two | first::others -> join' others (acc ^ first ^ ", ") in join' list "" erlang io:format("~s~n", [join(Fruit)]). % ------ join([]) -> ""; join([W|Ws]) -> join(Ws, W). join([], S) -> S; join([W], S) -> join([], S ++ " and " ++ W); join([W|Ws], S) -> join(Ws, S ++ ", " ++ W).%% According to the reference manual, "string is not a data type in Erlang." %% Instead it has lists of integers. But I/O functions in general accept %% IO lists, where an IO list is either a list of IO lists or an integer. %% This gives you O(1) string concatenation. -module(commalist). -export([join/1]). join([]) -> ""; join([W]) -> W; join([W1, W2]) -> [W1, " and ", W2]; join([W1, W2, W3]) -> [W1, ", ", W2, ", and ", W3]; join([W1|Ws]) -> [W1, ", ", join(Ws)].

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5] , produce the list: [["a", 4] , ["b", 4] , ["c", 4] , ["a", 5] , ["b", 5] , ["c", 5] ] ocaml let combinations = let l1 = ["a"; "b"; "c"] and l2 = [4; 5] in List.rev ( List.fold_left (fun acc y -> List.fold_left (fun acc2 x -> (x, y)::acc2 ) acc l1 ) [] l2 ) erlang Combinations = lists:foldl(fun (Number, Acc) -> Acc ++ lists:map(fun (Letter) -> {Letter, Number} end, Letters) end, [], Numbers),Combinations = lists:keysort(2, sofs:to_external(sofs:product(sofs:set(Letters), sofs:set(Numbers)))) [[A, B] || A <- ["a", "b", "c"], B <- [4, 5]].

From a List Produce a List of Duplicate Entries

Taking a list: ["andrew", "bob", "chris", "bob"] Write the code to produce a list of duplicates in the list: ["bob"] ocaml let rem v lst = let rec aux acc = function | [] -> List.rev acc | x::xs -> if compare v x = 0 then aux acc xs else aux (x::acc) xs in aux [] lst (** in case of a match, returns a list with the duplicate(s) removed *) let rec mem_rem v lst = let rec aux acc = function | [] -> None | x::xs -> if compare v x = 0 then Some(List.rev_append acc (rem v xs)) else aux (x::acc) xs in aux [] lst let duplicates lst = let rec aux acc = function | [] -> List.rev acc | x::xs -> match mem_rem x xs with | Some ret -> aux (x::acc) ret | None -> aux acc xs in aux [] lst let () = let lst = ["andrew"; "bob"; "chris"; "bob"; "mike"; "peter"; "bob"] in let dup = duplicates lst in List.iter print_endline dup(* Using standard (functorized) sets *) module SetTools(ASet: Set.S) = struct let find_duplicates l = let rec aux l seen acc = match l with | [] -> acc | h :: q -> if ASet.mem h seen then aux q seen (h :: acc) else aux q (ASet.add h seen) acc in aux l (ASet.empty) [] end module StringSet = Set.Make(String) module StringSetTools = SetTools(StringSet) StringSetTools.find_duplicates ["andrew"; "bob"; "chris"; "bob"];; erlang {_, Result} = lists:foldl( fun(X, {Uniq, Dupl}) -> case lists:member(X, Uniq) of true -> {Uniq,[X | Dupl]}; _ -> {[X | Uniq], Dupl} end end, {[], []}, List),Fun = fun ([X | Xs], F) -> case lists:member(X, Xs) of true -> [X | F(Xs, F)]; _ -> F(Xs, F) end; ([], _) -> [] end, Result = Fun(List, Fun). Access

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five] , fetch the third element ( 'Three' ) ocaml let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;; erlang Result = lists:nth(3, List),Result = element(3, list_to_tuple(List)),{Left, _} = lists:split(3, List), Result = lists:last(Left),Result = nth0(2, List),

Fetch the last element of a list

Given the list [Red, Green, Blue] , access the last element ( 'Blue' ) ocaml let list = [ "Red"; "Green"; "Blue" ] in let last = List.nth list ( (List.length list) - 1 );;let list = [ "Red"; "Green"; "Blue" ] in let last = List.hd (List.rev list);;let list_last l = let rec aux h q = match q with | [] -> h | h :: q -> aux h q in match l with | [] -> invalid_arg "list_last" | h :: q -> aux h q ;; list_last ["Red"; "Green"; "Blue"] erlang Result = lists:last(List),Result = last(List),Result = hd(lists:reverse(List)),Result = lists:nth(length(List), List),

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'] , what are the bean varieties that are also color names? ocaml let beans = ["broad"; "mung"; "black"; "red"; "white"] let colors = ["black"; "red"; "blue"; "green"] let f common c = if List.mem c beans then c::common else common let common = List.fold_left f [] colors;; (* common will contain a list with the common elements *)(* using standard (functorized) sets *) module SetTools(ASet: Set.S) = struct let of_list l = List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l let find_common l1 l2 = ASet.elements (ASet.inter (of_list l1) (of_list l2)) end module StringSet = Set.Make(String) module StringSetTools = SetTools(StringSet) ;; let beans = ["broad"; "mung"; "black"; "red"; "white"] in let colors = ["black"; "red"; "blue"; "green"] in StringSetTools.find_common beans colors;; erlang Beans = sets:from_list([broad, mung, black, red, white]), Colors = sets:from_list([black, red, blue, green]), Common = sets:to_list(sets:intersection(Beans, Colors)),

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18] , display the unique elements, i.e. with duplicates removed. ocaml let ages = [18; 16; 17; 18; 16; 19; 14; 17; 19; 18] let f res e = if List.mem e res then res else e::res let unique = List.fold_left f [] ages;;(* using standard (functorized) sets *) module SetTools(ASet: Set.S) = struct let of_list l = List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l let unique l = ASet.elements (of_list l) end module Integer = struct type t = int let compare (x:t) y = Pervasives.compare x y end module IntegerSet = Set.Make(Integer) module IntegerSetTools = SetTools(IntegerSet) ;; IntegerSetTools.unique [18; 16; 17; 18; 16; 19; 14; 17; 19; 18];; let removeDuplicate list = let rec aux acc = function | [] -> acc | h :: t -> if (List.mem h t) then aux acc t else aux (h::acc) t in List.rev (aux [] list);; erlang Ages = sets:to_list(sets:from_list([18, 16, 17, 18, 16, 19, 14, 17, 19, 18])), io:format("~w~n", [Ages]).lists:usort([18, 16, 17, 18, 16, 19, 14, 17, 19, 18]). Modification

Remove an element from a list by index

Given the list [Apple, Banana, Carrot] , remove the first element to produce the list [Banana, Carrot] ocaml let delete_at i al = if i < 0 || i >= List.length al then invalid_arg "delete_at" else let rec del i l = match l with | [] -> [] | h::t when i = 0 -> t | h::t -> h :: del (i-1) t in del i al ;;let rem_first l = match l with | [] -> [] | h::t -> t ;;List.tl ["Apple"; "Banana"; "Carrot"] erlang Result = tl(List),[_|Result] = List,N = 1, {Left, Right} = lists:split(N - 1, List), Result = Left ++ tl(Right),Result = drop(1, List),

Remove the last element of a list

ocaml let remove_last list = match (List.rev list) with | h::t -> List.rev t | [] -> []let remove_last lst = List.rev (List.tl (List.rev lst))let list_remove_last l = let rec aux h q acc = match q with | [] -> List.rev acc | h2 :: q -> aux h2 q (h :: acc) in match l with | [] -> invalid_arg "list_remove_last" | h :: q -> aux h q [] erlang Result = init(List),Result = take(length(List) - 1, List),Result = lists:reverse(tl(lists:reverse(List))),lists:sublist(List,length(List)-1)

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"] , rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"] ocaml let rotate list = match list with | head::tail -> tail@[head] | [] -> [] erlang N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,N = 1, Result = rotate(N, List), Manipulation

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'] , last = ['Willis', 'Jones', 'Lee'] , years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones. ocaml let rec combine3 f l y = match f, l, y with | [], [], [] -> [] | fh :: fq, lh :: lq, yh :: yq -> (fh, lh, yh) :: combine3 fq lq yq | _ -> invalid_arg "combine3" ;; let first = ["Bruce"; "Tommy Lee"; "Bruce"] in let last = ["Willis"; "Jones"; "Lee"] in let years = [1955; 1946; 1940] in combine3 first last years erlang First = ['Bruce', 'Tommy Lee', 'Bruce'], Last = ['Willis', 'Jones', 'Lee'], Years = [1955, 1946, 1940], Result = lists:zip3(First, Last, Years),

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] , generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts' . ocaml let suites = ["H"; "D"; "C"; "S"] let faces = ["2";"3";"4";"5";"6";"7";"8";"9";"10";"J";"Q";"K";"A"] let desk = List.fold_left (fun acc y -> List.fold_left (fun acc2 x -> (x, y)::acc2 ) acc faces ) [] suites let () = assert (List.length desk = 52); if List.mem ("A", "H") desk then print_endline "Ace of Hearts found!" else print_endline "Ace of Hearts not found :(" erlang Cards = lists:foldl(fun (Suite, Acc) -> Acc ++ lists:flatmap(fun (Face) -> [{Suite, Face}] end, Faces) end, [], Suites), io:format("Deck has ~B cards~n", [length(Cards)]), IsMember = lists:member({h, 'A'}, Cards), io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),Cards = sofs:to_external(sofs:product(sofs:set(Suites), sofs:set(Faces))), io:format("Deck has ~B cards~n", [length(Cards)]), IsMember = lists:member({h, 'A'}, Cards), io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),Deck2 = [{S, V} || S <- [d, c, h, s], V <- [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']], 52 = length(Deck2), true = lists:member({h, 'A'}, Deck2).

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g. for the list ["ox", "cat", "deer", "whale"] calculate the list of sizes of the strings, e.g. [2, 3, 4, 5] ocaml List.map String.length ["ox"; "cat"; "deer"; "whale"];; erlang lists:map(fun (X) ->length(X) end, List).

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date, split the list into numbers and non-numbers. ocaml (* OCaml is a strongly statically typed language so it is not possible to mix items of different types in a single list. So here we use a list of strings, some of these strings represent a number *) let is_a_number v = try ignore(float_of_string v); true with _ -> false let numbers, others = List.partition is_a_number ["Joe"; "3.14"; "8"; "hello"; "23/04/2009"] (* ========================================================================== *) (* If we really want to mix items of several types, we can declare a variant: *) type item = Int of int | Float of float | String of string | Char of char let is_a_number = function | Float _ | Int _ -> true | String _ | Char _ -> false let numbers, others = List.partition is_a_number [String "Joe"; Float 3.14; Int 8; Char 'Z'] erlang % Wrapped call to the auxiliary function number_split(Xs) -> number_split(Xs, [], []). % The auxiliary function number_split([], Num, NonNum) -> {Num, NonNum}; number_split([X|Xs], Num, NonNum) -> case is_number(X) of true -> number_split(Xs, [X|Num], NonNum); false -> number_split(Xs, Num, [X|NonNum]) end.List = ["hello", 25, 3.14, calendar:local_time()], {Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List) Testing

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list. ocaml (* from the interactive loop *) # List.for_all (fun x -> x > 1) [2; 3; 4] ;; - : bool = true erlang Result = lists:all(Pred, List).

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list. ocaml (* from the interactive loop: *) # List.exists (fun x -> x > 3) [2; 3; 4] ;; - : bool = true erlang Result = lists:any(Pred, List). Maps Declaration

Define an empty map

ocaml module StringMap = Map.Make (String) let m = StringMap.emptylet m = Hashtbl.create 42 erlang Map = dict:new(),Map = orddict:new(),Map = gb_trees:empty(),Map = ets:new(the_map_name, [set, private, {keypos, 1}]),

Define an unmodifiable empty map

ocaml (* OCaml maps are functional data structures (so are immutable) *) module StringMap = Map.Make (String) let m = StringMap.empty erlang % Erlang data structures are immutable - updating a 'map' sees a modified copy created Map = dict:new(),

Define an initial map

Define the map {circle:1, triangle:3, square:4} ocaml module StringMap = Map.Make (String) let m0 = StringMap.empty let m1 = StringMap.add "circle" 1 m0 let m2 = StringMap.add "triangle" 3 m1 let m3 = StringMap.add "square" 4 m2let m = Hashtbl.create 42;; Hashtbl.replace m "circle" 1;; Hashtbl.replace m "triangle" 3;; Hashtbl.replace m "square" 4;; erlang Map = dict:from_list([{circle, 1}, {triangle, 3}, {square, 4}]),Map0 = dict:new(), % Erlang variables are 'single-assignment' i.e. they cannot be reassigned Map1 = dict:store(circle, 1, Map0), Map2 = dict:store(triangle, 3, Map1), Map3 = dict:store(square, 4, Map2),Map0 = gb_trees:empty(), Map1 = gb_trees:enter(circle, 1, Map0), Map2 = gb_trees:enter(triangle, 3, Map1), Map3 = gb_trees:enter(square, 4, Map2),Map = gb_trees:from_orddict(lists:keysort(1, [{circle, 1}, {triangle, 3}, {square, 4}])),Map = ets:new(the_map_name, [ordered_set, private, {keypos, 1}]), ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]), Access

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary" ocaml module StringMap = Map.Make (String) let map = List.fold_left (fun map (key, value) -> StringMap.add key value map ) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")] let () = if StringMap.mem "mary" map then print_endline "OK"let () = let map = Hashtbl.create 42 in List.iter (fun (key, value) -> Hashtbl.add map key value ) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]; if Hashtbl.mem map "mary" then print_endline "OK" erlang dict:is_key(mary, Pets) andalso begin io:format("ok~n"), true end.IsMember = ets:member(Pets, mary), if (IsMember) -> io:format("ok~n") ; true -> false end.case gb_trees:lookup(mary, Pets) of none -> false ; _ -> io:format("ok~n") end.

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ( "cat" ) ocaml module StringMap = Map.Make (String) let map = List.fold_left (fun map (key, value) -> StringMap.add key value map ) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")] let () = try let pet = StringMap.find "joe" map in Printf.printf "Joe's pet is a %s.\n" pet with Not_found -> prerr_endline "No pet found for Joe."let () = let map = Hashtbl.create 42 in List.iter (fun (key, value) -> Hashtbl.add map key value ) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]; try let pet = Hashtbl.find map "joe" in Printf.printf "Joe's pet is a %s.\n" pet with Not_found -> prerr_endline "No pet found for Joe." erlang dict:is_key(joe, Pets) andalso begin io:format("~w~n", [dict:fetch(joe, Pets)]), true end.case dict:find(joe, Pets) of error -> false ; {ok, Pet} -> io:format("~w~n", [Pet]) end.IsMember = ets:member(Pets, joe), if (IsMember) -> io:format("~w~n", [ets:lookup_element(Pets, joe, 2)]) ; true -> false end.case ets:match(Pets, {joe, '$1'}) of [] -> false ; [[Pet]] -> io:format("~w~n", [Pet]) end.case gb_trees:lookup(joe, Pets) of none -> false ; {value, Pet} -> io:format("~w~n", [Pet]) end.

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog" ocaml module StringMap = Map.Make (String) let pets = StringMap.add "rob" "dog" StringMap.emptylet () = let map = Hashtbl.create 42 in Hashtbl.replace map "rob" "dog" erlang Pets1 = dict:store(rob, dog, Pets0).ets:insert(Pets, {rob, dog}).Pets1 = gb_trees:enter(rob, dog, Pets0).

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary" ocaml module StringMap = Map.Make (String) let pets = List.fold_left (fun map (key, value) -> StringMap.add key value map ) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")] let get_and_rem key m = try let value = StringMap.find key m in let rm = StringMap.remove key m in Some (value, rm) with Not_found -> None let () = let key = "bill" in match get_and_rem key pets with | Some (found, new_pets) -> Printf.printf "%s : %s removed\n" key found | None -> Printf.printf "Key %s not found" keylet get_and_rem m key = try let value = Hashtbl.find m key in Hashtbl.remove m key; Some value with Not_found -> None let () = let pets = Hashtbl.create 42 in List.iter (fun (key, value) -> Hashtbl.add pets key value ) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]; let key = "bill" in match get_and_rem pets key with | Some found -> Printf.printf "%s : %s removed\n" key found | None -> Printf.printf "Key %s not found" key erlang Pet = dict:fetch(bill, Pets0), Pets1 = dict:erase(bill, Pets0), io:format("~w~n", [Pet]),Pet = ets:lookup_element(Pets, bill, 2), ets:delete(Pets, bill), io:format("~w~n", [Pet]),{value, Pet} = gb_trees:lookup(bill, Pets0), Pets1 = gb_trees:delete(bill, Pets0), io:format("~w~n", [Pet]), Algorithms

Create a histogram map from a list

Given the list [a,b,a,c,b,b] , produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list ocaml module StringMap = Map.Make (String) let histogram lst = List.fold_left (fun m v -> let n = if StringMap.mem v m then succ (StringMap.find v m) else 1 in StringMap.add v n m ) StringMap.empty lst let () = let h = histogram ["a"; "b"; "a"; "c"; "b"; "b"] in StringMap.iter (fun key value -> Printf.printf " %s: %d\n" key value ) h erlang % Imperative Solution Histogram = histogram(List),% Functional (1) Solution Histogram = histogram(List),lists:foldl(fun(Elem, OldDict) -> dict:update_counter(Elem, 1, OldDict) end, dict:new(), [a,b,a,c,b,b])).

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length ocaml let map = List.fold_left (fun map v -> let len = String.length v in let before = try IntMap.find len map with Not_found -> [] in IntMap.add len (v :: before) map ) IntMap.empty ["one"; "two"; "three"; "four"; "five"] erlang % Imperative Solution CatList = categorise(List),% Functional (1) Solution CatList = categorise(List), Structure Conditionals

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob" , display the string "Hello, Bob!" . Perform no action if the name is not equal. ocaml if name = "Bob" then print_string "Hello, Bob!" erlang if (Name == "Bob") -> io:format("Hello, ~s!~n", [Name]) ; true -> false end.case Name of "Bob" -> io:format("Hello, ~s!~n", [Name]) ; _ -> false end.Name == "Bob" andalso (begin io:format("Hello, ~s!~n", [Name]), true end).

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old" , otherwise display "You are young" ocaml if age > 42 then print_string "You are old" else print_string "You are young" erlang if Age > 42 -> io:format("You are old~n") ; true -> io:format("You are young~n") end.Message = if Age > 42 -> "old" ; true -> "young" end, io:format("You are ~s~n", [Message]).case Age > 42 of true -> io:format("You are old~n") ; false -> io:format("You are young~n") end.case Age of _ when Age > 42 -> io:format("You are old~n") ; _ -> io:format("You are young~n") end.Message = case Age of _ when Age > 42 -> "old" ; _ -> "young" end, io:format("You are ~s~n", [Message]).Age > 42 andalso (begin io:format("You are old~n"), true end) orelse (begin io:format("You are young~n"), true end).(fun (X) when X > 42 -> io:format("You are old~n"); (_) -> io:format("You are young~n") end)(Age).(fun () when Age > 42 -> io:format("You are old~n"); () -> io:format("You are young~n") end)().io:format("You are ~s~n", [if Age > 42 -> "old" ; true -> "young" end]).

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

ocaml if age > 84 then print_endline "You are really ancient" else if age > 30 then print_endline "You are middle-aged" else print_endline "You are young" erlang if Age > 84 -> io:format("You are really ancient~n"); Age > 30 -> io:format("You are middle-aged~n"); true -> io:format("You are young~n") end.case Age of _ when Age > 84 -> io:format("You are really ancient~n"); _ when Age > 30 -> io:format("You are middle-aged~n"); true -> io:format("You are young~n") end.

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th ocaml let numsuffix i = match i with | 11 | 12 | 13 -> "th" | x when x mod 10 = 1 -> "st" | x when x mod 10 = 2 -> "nd" | x when x mod 10 = 3 -> "rd" | _ -> "th" ;; (* alternate implementation without using guards: let numsuffix i = match i with | 11 | 12 | 13 -> "th" | x -> match x mod 10 with | 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th" *) for i = 1 to 40 do Printf.printf "%d%s " i (numsuffix i); done; print_newline () erlang Suffix = case Num of N when N > 10, N < 20 -> "th"; N when N rem 10 =:= 1 -> "st"; N when N rem 10 =:= 2 -> "nd"; N when N rem 10 =:= 3 -> "rd"; _ -> "th" end, io_lib:format("~w~s", [Num, Suffix]) Loops

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150. ocaml let x = ref 1 ;; while !x < 150 do Printf.printf "%d," !x; x := !x * 2; done; print_newline() erlang X = 1, print_while_X_less_150(X).Pred = fun (X) -> X < 150 end, Action = fun (X) -> io:format("~B,", [X]), X * 2 end, X = 1, while_do(Pred, Action, X).

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6" ocaml let () = Random.self_init (); let rec loop () = let n = (Random.int 6) + 1 in print_int n; if n <> 6 then (print_char ','; loop ()) else print_newline () in loop () erlang Pred = fun (DiceRoll) -> DiceRoll =/= 6 end, Action = fun (DiceRoll) -> io:format("~B,", [DiceRoll]), dice_roll() end, do_while(Pred, Action, dice_roll()).-module(dice). -export([start/0]). start() -> roll(dice_roll()). roll(6) -> io:format("6~n", []); roll(N) -> io:format("~B,", [N]), roll(dice_roll()). dice_roll() -> random:uniform(6).

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello" ocaml let rec write_hello = function 0 -> () | n -> print_string "Hello" ; write_hello (n-1) ;; write_hello 5;;let write_hello n = for i = 1 to n do print_string "Hello"; done let () = write_hello 5 erlang dotimes(5, fun () -> io:format("Hello") end).lists:foreach(fun (_) -> io:format("Hello") end, lists:seq(1, 5)).

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!" ocaml for i = 10 downto 1 do Printf.printf "%d .. " i done; print_endline "Liftoff!" erlang fromto(10, 1, -1, fun (X) -> io:format("~B .. ", [X]) end), io:format("Liftoff!~n").lists:foreach(fun (X) -> io:format("~B .. ", [X]) end, lists:seq(10, 1, -1)), io:format("Liftoff!~n"). Files Reading

Read the contents of a file into a string

ocaml let read_file f = let ic = open_in f in let n = in_channel_length ic in let s = String.create n in really_input ic s 0 n; close_in ic; (s) let file_contents = read_file "file.txt" erlang Text = readfile("Solution607.erl"),Text = readfile("Solution608.erl"),

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like: 1> First line of file 2> Second line of file 3> Third line of file ocaml let () = let ic = open_in Sys.argv.(1) in let i = ref 1 in try while true do Printf.printf "%d> %s\n" !i (input_line ic); incr i done with End_of_file -> close_in iclet input_line_opt ic = try Some (input_line ic) with End_of_file -> None let () = let ic = open_in Sys.argv.(1) in let rec aux i = match input_line_opt ic with | Some line -> Printf.printf "%d> %s\n" i line; aux (succ i) | None -> close_in ic in aux 1 erlang Reader = fun (IODevice) -> io:get_line(IODevice, "") end, Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end, while_not_eof("Solution609.erl", Reader, Worker, 1).Reader = fun (Filename) -> {ok, Contents} = file:read_file(Filename), Contents end, Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end, Printer = fun (Line) -> io:format("~s~n", [Line]) end, Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"), NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))), lists:foreach(Printer, NewLines). Writing

Write a string to a file

ocaml try let cout = open_out filename in let co = Format.formatter_of_out_channel cout in Format.fprintf co "%s\n" text_to_write; close_out cout with Sys_error _ as e -> Format.printf "Cannot open file \"%s\": %s\n" filename (Printexc.to_string e) erlang Line = "This line overwites file contents!\n", {ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).

Append to a file

ocaml let () = let oc = open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0o666 "test.txt" in output_string oc "This line appended to file!\n"; close_out oc erlang Line = "This line appended to file!\n", {ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice). Directories

Process each file in a directory

ocaml let process dir file = if not (Sys.is_directory (Filename.concat dir file)) then print_endline file let () = let dir = "." in let files = Sys.readdir dir in Array.iter (process dir) files erlang % File basenames only - many tasks require absolute paths to work lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, file:list_dir(Directory)).% Absolute paths provided - will accomodate most tasks lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).

Process each file in a directory recursively

ocaml let rec recurse_dir dir f = let filenames = Sys.readdir dir in Array.iter (fun name -> let fullname = Filename.concat dir name in if Sys.is_directory fullname then recurse_dir fullname f else f fullname ) filenames ;; recurse_dir (Sys.getenv "HOME") print_endline ;; erlang filelib:fold_files(Directory, ".*", true, fun (FileOrDirPath, Acc) -> Worker(FileOrDirPath), Acc end, []).process_dir(Directory, Worker). Dates Parsing

Parse a date and time from a string

Given the string "2008-05-06 13:29" , parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone. ocaml let s = "2008-05-06 13:29" in let r = Str.regexp "\\([0-9][0-9][0-9][0-9]\\)-\\([0-9][0-9]\\)-\\([0-9][0-9]\\) \\([0-9][0-9]\\):\\([0-9][0-9]\\)" in assert (Str.string_match r s 0); Unix.mktime { Unix.tm_sec = 0; tm_min = int_of_string (Str.matched_group 5 s); tm_hour = int_of_string (Str.matched_group 4 s); tm_mday = int_of_string (Str.matched_group 3 s); tm_mon = int_of_string (Str.matched_group 2 s) - 1; tm_year = int_of_string (Str.matched_group 1 s) - 1900; tm_wday = -1; tm_yday = -1; tm_isdst = true; (** Daylight time savings in effect *) } erlang % AFAIK, no datetime-parsing library exists; 'parse_to_datetime' is a simplistic, problem-specific hack LocalDateTime = erlang:universaltime_to_localtime(parse_to_datetime("2008-05-06 13:29:34")), Printing

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now. ocaml let days = [| "Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday" |] let months = [| "January"; "February"; "March"; "April"; "May"; "June"; "July"; "August"; "September"; "October"; "November"; "December" |] let current_time = Unix.time () in let one_day = 86400. (* seconds *) in let future_time = Unix.localtime (current_time +. 8. *. one_day) in Printf.printf "day of month = %d, day of year = %d, month name = %s, day name = %s\n" future_time.Unix.tm_mday future_time.Unix.tm_yday months.(future_time.Unix.tm_mon) days.(future_time.Unix.tm_wday)

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like: Thursday, January 1, 2009 jeudi 1 janvier 2009 giovedì 1 gennaio 2009 Donnerstag, 1. Januar 2009 donderdag 1 januari 2009 (Indicate in comments where possible if any language specific or operating system configuration needs to be in place.) Creation

Display the current date and time

Create a Date object representing the current date and time. Print it out. If you can also do this without creating a Date object you can show that too. ocaml Unix.localtime (Unix.gettimeofday ()) erlang io:format("~p~n", [calendar:local_time()]) OOP Basics

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method. ocaml class greeter message = object method greet = print_endline message end let o = new greeter "Hello" in o#greet erlang Greeter = make_greeter("world!"), Greeter(greet).


zwarte horloges voor mannen

Breitling Superocean Heritage
gli orologi di modo delle signore
relojes de pulsera para mujer
cartier umar

ZWARTE HORLOGES

Zwart: de basiskleur voor modern minimalisme, zonder compromis. De zwarte horloges van CLUSE zijn verguld met een zwarte titanium finish. Geborsteld voor een ingetogen matte look. Mysterieus opvallend met premium elegantie.

Meer ontdekken: Zwart fluwelen armband | Zwarte cadeauset

La Bohème Full Black
€8995
Minuit Full Black/Nude
€8995
La Bohème Full Black/Nude
€8995
La Bohème Mesh Full Black
€9995
Minuit Full Black
€8995
Minuit Mesh Full Black
€9995
La Roche Full Black/White Marble
€12995
La Roche Full Black Marble
€12995
La Vedette Full Black
€8995
La Vedette Mesh Full Black
€9995
Strap 18 mm - Full Black
Past bij: La Bohème, La Roche & Pavane
€2995
Strap 16 mm - Full Black
Past bij: Minuit & La Roche Petite
€2995
Strap 12 mm - Full Black
Past bij: La Vedette
€2995
Strap 12 mm - Mesh Full Black
Past bij: La Vedette
€3995
Sale
La Bohème Full Black/Mustard
89.95
€5995
Sale
Minuit Full Black/Mustard
89.95
€5995
Sale
La Bohème Full Black/Blue Denim
89.95
€5995
Sale
Minuit Full Black/Blue Denim
89.95
€5995
Uitverkocht
La Bohème Full Black/Olive Green
89.95
€5995
Sale
Minuit Full Black/Olive Green
89.95
€5995
CLUSE La Bohème Gift Box Full Black + Nude Strap
€9995

CLUSE ZWARTE HORLOGES - GEEF TOE AAN JE DUISTERE KANT

Zwart op zwart - ton-sur-ton zwarte details op een matzwarte wijzerplaat - of met een contrasterende witte marmeren wijzerplaat, zwart is tijdloos. Krachtig en stijlvol in ons grotere formaat La Bohème full black en in de La Roche full black collectie, als symbool voor de schoonheid van middernacht in Minuit full black of subtiel schitterend in de stijlvolle La Vedette full black.

EEN VLEUGJE EXTRA ZWARTE MAGIE

Ga voor een totaalbeleving en houd je niet in: maak je look helemaal af met een zwart leren of zwart mesh bandje. Of geef je stijl een verfrissende update en kies voor een accessoire met mysterieuze schittering voor bij je zwarte CLUSE-horloge: een verfijnde schakelarmband, onderbroken door zes zwarte kristallen. In goud, roségoud of zilver - onderdeel van de Idylle-sieradencollectie

MEER ONTDEKKEN ZWARTE HORLOGES VOOR DAMES

Zwarte & gouden horloges | Zwarte & roségouden Horloges | Volledig zwarte horloges