The most asked OCaml interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 119 min read
99 OCaml interview questions, grouped by level: freshers, intermediate, experienced and coding.
Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
Use the filter bar to practise only the level you are interviewing for, then test yourself with the free OCaml quiz.
What is OCaml, and why do interviewers ask about it?
This page provides a complete collection of OCaml Interview Questions and Answers designed for functional programmers, systems developers, and software engineers preparing for technical interviews.
OCaml (Objective Caml) is a powerful statically-typed functional programming language with a strong type system, pattern matching, and a sophisticated module system. It is used in finance, formal verification, compiler development, and many other domains.
This interview guide covers beginner, intermediate, and advanced OCaml concepts including syntax, recursion, data structures, modules, functors, monads, concurrency, FFI, and real-world functional programming patterns.
Why companies hire for OCaml
Strong static type inference – catches errors at compile time, reduces runtime bugs
Quick answerOCaml is a statically-typed functional programming language with object-oriented features. It is known for its strong type system, pattern matching, and performance.
Functional: Functions are first-class citizens
Statically typed: Type-safe with type inference
Pattern matching: Powerful for data manipulation
Module system: Functors, signatures, and structures
Quick answerOCaml has a rich type system with primitive types, variants, records, and polymorphic types.
Integers: int
Floats: float
Booleans: bool
Characters: char
Strings: string
Tuples: (int * string)
Lists: int list
Arrays: int array
Records: { name: string; age: int }
Variants: type color = Red | Green | Blue
Ocaml
# DataTypesinOCaml
# Integer types
let a = 10(* int *)let b = 127(* int *)
# Floating point
let d = 3.14(* float *)let e = 2.5(* float *)
# Stringlet f = "Hello OCaml"
# Booleanlet g = truelet h = false
# Characterlet c = 'A'
# Tuplelet j = (1, "hello", 3.14)
# Listlet k = [1; 2; 3; 4; 5]
# Arraylet l = [|1; 2; 3; 4; 5|]
# Recordtypetype person = { name: string; age: int }
let alice = { name = "Alice"; age = 25 }
let() =
print_endline (string_of_int a)
Quick answerFunctions in OCaml are defined using the let keyword. Functions can be recursive and can use pattern matching.
Definition: let add a b = a + b
Recursive: let rec factorial n = ...
Pattern matching: function | ... -> ...
Anonymous functions: fun x -> x * x
Partial application: let add5 = add 5
Ocaml
# FunctionsinOCaml
# Function declaration
let add a b = a + b
# Recursivefunctionletrec factorial n =
if n <= 1then1else n * factorial (n - 1)
# Functionwith pattern matching
letrec fibonacci n =
match n with
| 0 -> 0
| 1 -> 1
| n -> fibonacci (n - 1) + fibonacci (n - 2)
# Anonymousfunctionlet square = fun x -> x * x
let double x = x * 2
# Higher-order functions
let apply_twice f x = f (f x)
# Partial application
let add5 = add 5let() =
print_int (add 53);
print_endline "";
print_int (factorial 5);
print_endline "";
print_int (square 4);
print_endline ""
Quick answerAssociation lists are lists of pairs used as key-value stores. They provide simple dictionary-like functionality.
Creation: [("name", "Alice"); ("age", "25")]
Access: List.assoc "name" dict
Add/Update: ("country", "USA") :: dict
Check: List.mem_assoc "name" dict
Alternative: Use Map module for efficiency
Ocaml
# AssociationLists (Maps) inOCaml
# Create association listlet person = [("name", "Alice"); ("age", "25"); ("city", "NYC")]
# Access values using List.assoc
let name = List.assoc "name" person
let age = List.assoc "age" person
# Add/update values (creating newlist)
let person2 = ("country", "USA") :: person
# Checkif key exists
let has_name = List.mem_assoc "name" person
# Iterate over association listlet() =
List.iter (fun (key, value) ->
Printf.printf "%s: %s\n" key value
) person
# UsingMapmodulefor efficient key-value pairs
moduleStringMap = Map.Make(String)
let map = StringMap.empty
let map2 = StringMap.add "name""Alice" map
let name2 = StringMap.find "name" map2
Quick answerTuples are immutable ordered collections of values that can have different types.
Creation: (1, "hello", 3.14, true)
Access: Use pattern matching
Unpacking: let (a, b, c) = tuple
Named tuples: Not supported directly, use records
Pattern matching: match (x, y) with (0, 0) -> ...
Ocaml
# TuplesinOCaml
# Create tuple
let t = (1, "hello", 3.14, true)
# Access elements using pattern matching
let (a, b, c, d) = t
let first = let (x, _, _, _) = t in x
# Function returning multiple values
let divide a b = (a / b, a mod b)
let quotient, remainder = divide 103
# Tupleof tuples
let nested = ((1, 2), (3, 4))
# Pattern matching on tuples
let describe_tuple (x, y) =
match (x, y) with
| (0, 0) -> "Origin"
| (_, 0) -> "On x-axis"
| (0, _) -> "On y-axis"
| _ -> "Somewhere else"let() =
Printf.printf "Quotient: %d, Remainder: %d\n" quotient remainder
Quick answerOCaml uses if and match for control flow. Loops are implemented using recursion.
If-else: if condition then ... else ...
Pattern matching: match expression with | ... -> ...
For loops: for i = 1 to 10 do ... done
While loops: while condition do ... done
Recursion: Preferred for iteration
Ocaml
# ControlFlowinOCaml
# If-else statement
let age = 25inlet status =
if age < 18then"Minor"elseif age < 65then"Adult"else"Senior"in
print_endline status
# Pattern matching
let describe_number n =
match n with
| 0 -> "Zero"
| 1 -> "One"
| 2 -> "Two"
| _ -> "Other"
# For loop
let() =
for i = 1to5do
print_int i;
print_char '\n'done
# While loop
let() =
let i = ref1inwhile !i <= 5do
print_int !i;
print_char '\n';
i := !i + 1done
# Recursion (preferred inOCaml)
letrec print_numbers n =
if n <= 0then()else (
print_int n;
print_char '\n';
print_numbers (n - 1)
)
# UsingList.iter for iteration
let fruits = ["apple"; "banana"; "orange"]
let() = List.iter print_endline fruits
# StringsinOCaml
# String creation
let str1 = "Hello"let str2 = "World"let str3 = "Multi-line\nstring"
# String concatenation
let greeting = str1 ^ " " ^ str2
# String interpolation using Printflet name = "OCaml"let version = 4.14let message = Printf.sprintf "Welcome to %s version %.2f" name version
# String functions
let text = "Hello, World!"let length = String.length text
let uppercase = String.uppercase_ascii text
let lowercase = String.lowercase_ascii text
# Substringlet sub = String.sub text 05
# Splitand join
let words = String.split_on_char ' '"Hello World OCaml"let joined = String.concat "-" words
# String comparison
let cmp1 = "hello" = "hello"let cmp2 = "hello" < "world"
# Character operations
let first_char = text.[0]
let char_code = int_of_char 'A'
# String formatting
let formatted = Printf.sprintf "Value: %.2f"3.14159let() =
print_endline greeting;
print_endline message;
print_endline uppercase
Quick answerModules in OCaml provide a way to organize code, encapsulate implementation details, and define interfaces.
Definition: module MyModule = struct ... end
Signature: module type NAME = sig ... end
Functors: Modules parameterized by modules
Include: include Module
Open: open Module
Ocaml
# ModulesinOCaml
# Defining a module using structmoduleMyMath = structlet pi = 3.14159let add a b = a + b
let subtract a b = a - b
let multiply a b = a * b
let divide a b = a / b
end
# Using a modulelet result = MyMath.add 53let pi_value = MyMath.pi
# Module signature (interface)
moduletypeMATH = sigval pi : floatval add : int -> int -> intval subtract : int -> int -> intend
# Implementing a modulewith signature
moduleMyMath2 : MATH = structlet pi = 3.14159let add a b = a + b
let subtract a b = a - b
let multiply a b = a * b (* Hidden from signature *)end
# Functors (modules parameterized by modules)
moduletypeORDERED = sigtype t
val compare : t -> t -> intendmoduleSet = functor (M: ORDERED) -> structtype t = M.t listlet empty = []let add x set = x :: set
end
# Opening modules
openMyMathlet sum = add 105let() =
print_int result;
print_endline ""
Quick answerOCaml has a powerful type system with built-in and user-defined types. Types are inferred but can also be explicitly specified.
Built-in types: int, float, string, bool
Variant types: type color = Red | Green | Blue
Record types: type person = { name: string; age: int }
Polymorphic types: 'a option
Abstract types: Defined in signatures
Ocaml
# TypesinOCaml
# Basictype definitions
type int_list = intlisttype string_pair = string * string
# Variant types (sum types)
type color =
| Red
| Green
| Blue
| RGBofint * int * int
# Record types (product types)
type person = {
name: string;
age: int;
city: string;
}
# Typewith parameters (polymorphic)
type'a option =
| None
| Someof'a
# Recursive types
type tree =
| Empty
| Nodeofint * tree * tree
# Type abbreviations
type point = float * float
# Abstract types
moduletypeABSTRACT = sigtype t
val create : int -> t
valvalue : t -> intend
# Usagelet alice = { name = "Alice"; age = 25; city = "NYC" }
let color = RGB(255, 0, 0)
# Pattern matching on types
let get_name person = person.name
let get_age { age; _ } = age
let describe_color = function
| Red -> "Red"
| Green -> "Green"
| Blue -> "Blue"
| RGB(r, g, b) -> Printf.sprintf "RGB(%d, %d, %d)" r g b
let() =
print_endline (describe_color color);
print_int (get_age alice);
print_endline ""
Quick answerPattern matching is a core feature of OCaml that allows deconstruction of data structures and control flow based on structure.
Basic: match x with | 0 -> "zero" | _ -> "non-zero"
Lists: match lst with [] -> ... | h :: t -> ...
Records: match person with { name; age } -> ...
Guards: match n with x when x < 0 -> "negative"
Nested: Pattern matching can be nested
Ocaml
# PatternMatchinginOCaml
# Basic pattern matching
let is_zero n =
match n with
| 0 -> true
| _ -> false
# Pattern matching on lists
letrec sum_list lst =
match lst with
| [] -> 0
| head :: tail -> head + sum_list tail
# Pattern matching with guards
let classify_number n =
match n with
| 0 -> "Zero"
| x when x < 0 -> "Negative"
| x when x > 0 -> "Positive"
| _ -> "Unknown"
# Pattern matching on tuples
let add_tuple (x, y) = x + y
# Pattern matching on records
let describe_person { name; age; city } =
Printf.sprintf "%s is %d years old from %s" name age city
# Nested pattern matching
letrec sum_tree = function
| Empty -> 0
| Node(value, left, right) ->
value + sum_tree left + sum_tree right
# Pattern matching withOR patterns
let is_zero_or_one n =
match n with
| 0 | 1 -> true
| _ -> false
# Functionwith multiple patterns
letrec fibonacci n =
match n with
| 0 -> 0
| 1 -> 1
| n -> fibonacci (n - 1) + fibonacci (n - 2)
let() =
print_int (sum_list [1; 2; 3; 4; 5]);
print_endline ""
Quick answerOCaml provides exception handling using try and with blocks, with custom exceptions and pattern matching.
Definition: exception MyException of string
Raise: raise (MyException "error")
Catch: try ... with | MyException msg -> ...
Finally: Use nested try blocks
Print: Printexc.to_string
Ocaml
# ExceptionHandlinginOCaml
# Exception definition
exceptionDivision_by_zeroexceptionInvalid_inputofstring
# Raising exceptions
let divide a b =
if b = 0then raise Division_by_zeroelse a / b
# Try-catch block
let safe_divide a b =
trySome (divide a b)
with
| Division_by_zero -> None
| Invalid_input msg ->
Printf.printf "Invalid input: %s\n" msg;
None
# Multipleexception handlers
let process_file filename =
trylet ic = open_in filename inlet content = really_input_string ic (in_channel_length ic) in
close_in ic;
content
with
| Sys_error msg ->
Printf.printf "System error: %s\n" msg;
""
| End_of_file ->
Printf.printf "Empty file\n";
""
| e ->
Printf.printf "Unexpected error: %s\n" (Printexc.to_string e);
""
# Using finally pattern
let with_file filename f =
let ic = open_in filename intrylet result = f ic in
close_in ic;
result
with e ->
close_in ic;
raise e
# Customexceptionwith data
exceptionErrorof { code: int; message: string }
let handle_error e =
match e with
| Error { code; message } ->
Printf.printf "Error %d: %s\n" code message
| _ -> print_endline "Unknown error"let() =
match safe_divide 100with
| Some result -> print_int result
| None -> print_endline "Cannot divide by zero"
Quick answerOCaml provides standard library functions for file I/O using channels. Common operations include reading, writing, and appending.
Read: open_in, input_line, close_in
Write: open_out, output_string, close_out
Append: open_out_gen [Open_append]
CSV: Manual parsing or using libraries
Try-catch: Handle file errors
Ocaml
# FileI/OinOCaml
# Reading files
let read_file filename =
let ic = open_in filename inlet content = really_input_string ic (in_channel_length ic) in
close_in ic;
content
# Reading line by line
let read_lines filename =
let ic = open_in filename inlet lines = ref[]intrywhiletruedo
lines := input_line ic :: !lines
done;
[]withEnd_of_file ->
close_in ic;
List.rev !lines
# Writing files
let write_file filename content =
let oc = open_out filename in
output_string oc content;
close_out oc
# Appendingto files
let append_file filename content =
let oc = open_out_gen [Open_append; Open_creat; Open_text] 0o644 filename in
output_string oc content;
close_out oc
# Using with_file pattern
let with_output_file filename f =
let oc = open_out filename intrylet result = f oc in
close_out oc;
result
with e ->
close_out oc;
raise e
# ReadingCSV (simple implementation)
let read_csv_line line =
String.split_on_char ',' line
# WritingCSVlet write_csv_row oc row =
output_string oc (String.concat "," row);
output_char oc '\n'let() =
write_file "example.txt""Hello, World!\nThis is line 2\n";
let content = read_file "example.txt"in
print_endline content
Quick answerOCaml provides various data structures through its standard library and Base/Core libraries including maps, sets, hashtables, queues, and stacks.
Map: Map.Make(String)
Set: Set.Make(String)
Hashtbl: Hashtbl.create
Queue: Queue.create
Stack: Stack.create
Ocaml
# DataStructuresinOCaml
# UsingBase library's DataStructuresopenCore
# Map (from Base)
moduleStringMap = Map.Make(String)
let map_example () =
let map = StringMap.empty inlet map = StringMap.set map ~key:"Alice" ~data:25inlet map = StringMap.set map ~key:"Bob" ~data:30inlet alice_age = StringMap.find_exn map "Alice"in
printf "Alice's age: %d\n" alice_age
# Set (from Base)
moduleStringSet = Set.Make(String)
let set_example () =
let set = StringSet.empty inlet set = StringSet.add set "Alice"inlet set = StringSet.add set "Bob"inlet has_alice = StringSet.mem set "Alice"in
printf "Has Alice: %b\n" has_alice
# Hashtbllet hash_example () =
let table = Hashtbl.create (moduleString) inHashtbl.set table ~key:"Alice" ~data:25;
Hashtbl.set table ~key:"Bob" ~data:30;
let alice_age = Hashtbl.find_exn table "Alice"in
printf "Alice's age: %d\n" alice_age
# Queuelet queue_example () =
let q = Queue.create ()inQueue.enqueue q 1;
Queue.enqueue q 2;
Queue.enqueue q 3;
while not (Queue.is_empty q) dolet x = Queue.dequeue_exn q in
printf "%d " x
done;
printf "\n"
# Stacklet stack_example () =
let s = Stack.create ()inStack.push s 1;
Stack.push s 2;
Stack.push s 3;
while not (Stack.is_empty s) dolet x = Stack.pop_exn s in
printf "%d " x
done;
printf "\n"let() =
map_example ();
set_example ();
hash_example ();
queue_example ();
stack_example ()
Quick answerOCaml provides linear algebra operations through the Owl library or by implementing matrix operations manually.
Owl: Mat.of_arrays, Mat.dot
Matrix multiplication: Implement manually
Eigenvalues: Mat.eigvals
Determinant: Mat.det
Inverse: Mat.inv
Ocaml
# LinearAlgebrainOCaml
# UsingOwl library for linear algebra
# (Requires: opam install owl)
openOwllet linear_algebra_example () =
let a = Mat.of_arrays [|
[|1.; 2.; 3.|];
[|4.; 5.; 6.|];
[|7.; 8.; 10.|]
|] inlet b = Mat.of_arrays [| [|1.|]; [|2.|]; [|3.|] |] in
# Matrix operations
let product = Mat.dot a b inlet transpose = Mat.transpose a in
# Solve linear systems
let x = Mat.linsolve a b in
# Eigenvalueslet eigenvals = Mat.eigvals a in
# Determinantlet det = Mat.det a in
# Inverselet inv = Mat.inv a in
# Matrix functions
let eye = Mat.eye 3inlet zeros = Mat.zeros 33inlet ones = Mat.ones 33inPrintf.printf "Determinant: %f\n" det
# UsingLinalgmodule from BaseopenBaselet simple_linear_algebra () =
let a = [| [|1.; 2.|]; [|3.; 4.|] |] inlet b = [| [|5.|]; [|6.|] |] in
# Matrix multiplication
let multiply a b =
let n = Array.length a inlet m = Array.length b.(0) inlet result = Array.make_matrix n m 0.0infor i = 0to n-1dofor j = 0to m-1dolet sum = ref0.0infor k = 0toArray.length a.(0)-1do
sum := !sum +. a.(i).(k) *. b.(k).(j)
done;
result.(i).(j) <- !sum
donedone;
result
inlet result = multiply a b inPrintf.printf "Matrix multiplication done\n"let() =
linear_algebra_example ();
simple_linear_algebra ()
Quick answerOCaml supports networking through various libraries including Cohttp for HTTP, Lwt for asynchronous networking, and the Unix module for TCP/UDP.
HTTP: Cohttp_lwt_unix.Client.get
WebSockets: WebSocket.Server.create
TCP: Unix.socket, Unix.connect
Server: Unix.listen, Unix.accept
Async: Lwt.async
Ocaml
# NetworkinginOCaml
# UsingLwtforHTTP client
openLwtopenCohttp_lwt_unixlet http_client_example () =
let uri = Uri.of_string "https://api.github.com"inClient.get uri >>= fun (response, body) ->
Body.to_string body >>= fun body_text ->
Lwt_io.printf "Response: %s\n" body_text
# HTTPServerlet http_server_example () =
let callback _conn req body =
let uri = req |> Request.uri inlet path = Uri.path uri inlet response_body = match path with
| "/" -> "Hello, World!"
| "/api" -> "API Endpoint"
| _ -> "Not Found"inServer.respond_string ~status:`OK ~body:response_body ()inlet server = Server.create ~mode:(`TCP (`Port8080)) (Server.make ~callback ()) inLwt.return ()
# WebSocket example
openWebSocketlet websocket_example () =
let server = WebSocket.Server.create ~port:8080inWebSocket.Server.on_connection server (fun ws ->
WebSocket.on_message ws (fun msg ->
Printf.printf "Received: %s\n" msg;
WebSocket.send ws ("Echo: " ^ msg)
)
)
# TCP client
let tcp_client_example () =
let host = "example.com"inlet port = 80inUnix.(gethostbyname host).h_addr_list.(0)
|> fun addr -> ADDR_INET (addr, port)
|> fun sockaddr ->
let sock = Unix.socket PF_INETSOCK_STREAM0inUnix.connect sock sockaddr;
let msg = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"inlet _ = Unix.send sock msg 0 (String.length msg) []inlet response = String.make 1024'\000'inlet len = Unix.recv sock response 01024[]inPrintf.printf "%s\n" (String.sub response 0 len);
Unix.close sock
# TCP server
let tcp_server_example () =
let server = Unix.socket PF_INETSOCK_STREAM0inUnix.setsockopt server SO_REUSEADDRtrue;
Unix.bind server (ADDR_INET (Unix.inet_addr_any, 8080));
Unix.listen server 5;
whiletruedolet (client, _) = Unix.accept server inlet msg = "Hello from server!\n"in
ignore (Unix.send client msg 0 (String.length msg) []);
Unix.close client
donelet() =
Printf.printf "Networking examples available\n"
# AbstractTypesandInterfaces
# Abstracttype definition
moduletypeANIMAL = sigtype t
val create : string -> int -> t
val name : t -> stringval age : t -> intval make_sound : t -> stringend
# Concrete implementation
moduleDog : ANIMAL = structtype t = { name: string; age: int }
let create name age = { name; age }
let name dog = dog.name
let age dog = dog.age
let make_sound _ = "Woof!"endmoduleCat : ANIMAL = structtype t = { name: string; age: int }
let create name age = { name; age }
let name cat = cat.name
let age cat = cat.age
let make_sound _ = "Meow!"end
# Using modules with same interface
let animal_example () =
let dog = Dog.create "Rex"3inlet cat = Cat.create "Whiskers"2inPrintf.printf "Dog: %s is %d years old\n" (Dog.name dog) (Dog.age dog);
Printf.printf "Cat: %s is %d years old\n" (Cat.name cat) (Cat.age cat);
Printf.printf "Dog says: %s\n" (Dog.make_sound dog);
Printf.printf "Cat says: %s\n" (Cat.make_sound cat)
# PolymorphicmodulemoduletypeCOLLECTION = sigtype'a t
val empty : 'a t
val add : 'a -> 'a t -> 'a t
val mem : 'a -> 'a t -> boolval fold : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'bend
# Interfacewith abstract typemoduletypeSTACK = sigtype'a t
val empty : 'a t
val push : 'a -> 'a t -> 'a t
val pop : 'a t -> 'a * 'a t
val peek : 'a t -> 'aval is_empty : 'a t -> boolend
# Implementing the stack interface
moduleListStack : STACK = structtype'a t = 'alistlet empty = []let push x s = x :: s
let pop = function
| [] -> failwith "Empty stack"
| h :: t -> (h, t)
let peek = function
| [] -> failwith "Empty stack"
| h :: _ -> h
let is_empty = function
| [] -> true
| _ -> falseendlet() =
animal_example ()
Quick answerParameterized (polymorphic) types in OCaml allow for generic programming and type-safe abstractions.
Definition: type 'a option = None | Some of 'a
Multiple parameters: type ('a, 'b) pair
Polymorphic functions: let identity x = x
GADTs: Generalized Algebraic Data Types
Functors: Modules parameterized by modules
Ocaml
# ParameterizedTypes (PolymorphicTypes)
# Basic parameterized typetype'a option =
| None
| Someof'atype ('a, 'b) pair = {
first: 'a;
second: 'b;
}
# Using parameterized types
let option_example () =
let x = Some42inlet y: int option = Some100inlet z: string option = Some"hello"inmatch x with
| Somevalue -> Printf.printf "Value: %d\n"value
| None -> print_endline "None"
# Polymorphic functions
let identity x = x
let compose f g x = f (g x)
# Polymorphiclist functions
letrec length = function
| [] -> 0
| _ :: t -> 1 + length t
letrec map f = function
| [] -> []
| h :: t -> f h :: map f t
# Type constraints
let add_ints (x: int) (y: int) = x + y
let add_floats (x: float) (y: float) = x +. y
# GADTs (GeneralizedAlgebraicDataTypes)
type _ expr =
| Int : int -> int expr
| Add : int expr * int expr -> int expr
| Bool : bool -> bool expr
| If : bool expr * 'a expr * 'a expr -> 'a expr
letrec eval : type a. a expr -> a = function
| Int i -> i
| Add (e1, e2) -> eval e1 + eval e2
| Bool b -> b
| If (cond, e1, e2) -> if eval cond then eval e1 else eval e2
# Higher-kinded polymorphism using modules
moduletypeFUNCTOR = sigtype'a t
val map : ('a -> 'b) -> 'a t -> 'b t
endmoduleListFunctor : FUNCTOR = structtype'a t = 'alistlet map = List.map
endlet() =
option_example ();
Printf.printf "Length: %d\n" (length [1; 2; 3; 4; 5]);
let expr = Add (Int2, Add (Int3, Int4)) inPrintf.printf "Eval: %d\n" (eval expr)
Quick answerMissing data in OCaml is handled using the option type ( None / Some) or the result type for error handling.
Missing data in OCaml is handled using the option type (None/Some) or the result type for error handling.
Option: type 'a option = None | Some of 'a
Result: type ('a, 'b) result = Ok of 'a | Error of 'b
Filter: List.filter_map
Default: Option.value ~default:0
Or_error: Or_error.return
Ocaml
# WorkingwithMissingData (Optiontype)
# UsingOptiontypefor missing data
openOptionlet option_example () =
# Creating values with missing data
let data = [Some1; Some2; None; Some4; Some5; None; Some7] in
# Checkfor missing values
let has_missing = List.exists Option.is_none data inPrintf.printf "Has missing: %b\n" has_missing
# Remove missing values
let clean_data = List.filter_map identity data inList.iter (fun x -> Printf.printf "%d " x) clean_data;
print_endline ""
# Replace missing values
let replaced = List.map (Option.value ~default:0) data inList.iter (fun x -> Printf.printf "%d " x) replaced;
print_endline ""
# Operationswith missing values
let x = [Some1; Some2; None; Some4] inlet y = [Some5; Some6; None; Some8] inlet z = List.map2 (fun a b ->
match a, b with
| Some a, Some b -> Some (a + b)
| _, _ -> None
) x y inList.iter (fun x ->
match x with
| Some v -> Printf.printf "%d " v
| None -> print_string "None "
) z;
print_endline ""
# Ignoring missing values
let sum_complete = List.fold_left (+)
(List.fold_left (fun acc x -> match x withSome v -> acc + v | None -> acc) 0 x)
0inPrintf.printf "Sum of complete data: %d\n" sum_complete
# UsingResulttypefor error handling
let result_example () =
let divide a b =
if b = 0thenError"Division by zero"elseOk (a / b)
inlet result1 = divide 102inlet result2 = divide 100inmatch result1 with
| Ok v -> Printf.printf "10/2 = %d\n" v
| Error e -> Printf.printf "Error: %s\n" e;
match result2 with
| Ok v -> Printf.printf "10/0 = %d\n" v
| Error e -> Printf.printf "Error: %s\n" e
# UsingOr_error from CoreopenCorelet or_error_example () =
let divide a b =
if b = 0thenOr_error.error "Division by zero"()elseOr_error.return (a / b)
inlet result = divide 102inmatch result with
| Ok v -> Printf.printf "Result: %d\n" v
| Error e -> Printf.printf "Error: %s\n" (Error.to_string e)
let() =
option_example ();
result_example ()
Quick answerCheck if a string is a palindrome by comparing characters from both ends.
Two-pointer: Compare from ends
Case insensitive: String.lowercase_ascii
Ignore spaces: String.filter
Fold: Compare to reversed
Ocaml
# Check palindrome
let is_palindrome s =
let len = String.length s inletrec check i =
if i >= len / 2thentrueelseif s.[i] = s.[len - 1 - i] then check (i + 1)
elsefalsein
check 0let is_palindrome_case_insensitive s =
let lower = String.lowercase_ascii s inlet len = String.length lower inletrec check i =
if i >= len / 2thentrueelseif lower.[i] = lower.[len - 1 - i] then check (i + 1)
elsefalsein
check 0let is_palindrome_with_spaces s =
let cleaned = String.filter (fun c -> c <> ' ') s in
is_palindrome cleaned
let is_palindrome_fold s =
let reversed = String.fold_left (fun acc c -> String.make 1 c ^ acc) "" s in
s = reversed
let() =
let test_strings = ["racecar"; "hello"; "A man a plan a canal Panama"; "race a car"] inList.iter (fun s ->
Printf.printf ""%s" is palindrome: %b\n" s (is_palindrome_case_insensitive s)
) test_strings
Quick answerRemove duplicate elements from a list using fold and membership test, or using sets.
Fold: List.fold_left
Set: Convert to set and back
Recursive: Helper with seen list
Preserve order: List.rev
Ocaml
# Remove duplicates
let remove_duplicates lst =
letrec helper seen result = function
| [] -> List.rev result
| h :: t ->
ifList.mem h seen then helper seen result t
else helper (h :: seen) (h :: result) t
in
helper [][] lst
let remove_duplicates_set lst =
let set = List.fold_left (fun acc x -> StringSet.add x acc) StringSet.empty lst inStringSet.to_list set
let remove_duplicates_fold lst =
List.fold_left (fun acc x ->
ifList.mem x acc then acc
else x :: acc
) [] lst
|> List.rev
let() =
let lst = ["apple"; "banana"; "apple"; "orange"; "banana"; "grape"] inPrintf.printf "Original: ";
List.iter (fun x -> Printf.printf "%s " x) lst;
print_endline "";
Printf.printf "Without duplicates: ";
List.iter (fun x -> Printf.printf "%s " x) (remove_duplicates lst);
print_endline "";
Printf.printf "Without duplicates (fold): ";
List.iter (fun x -> Printf.printf "%s " x) (remove_duplicates_fold lst);
print_endline ""
Quick answerConvert a string to a number using float_of_string or int_of_string with error handling.
Float: float_of_string
Int: int_of_string
Safe: float_of_string_opt
Error handling: try
Ocaml
# Convertstringto number
let string_to_float s =
try float_of_string s
withFailure _ -> 0.0let string_to_int s =
try int_of_string s
withFailure _ -> 0let string_to_float_safe s =
match float_of_string_opt s with
| Some v -> v
| None -> 0.0let string_to_int_safe s =
match int_of_string_opt s with
| Some v -> v
| None -> 0let string_to_number s =
tryifString.contains s '.'thenSome (float_of_string s)
elseSome (float_of_string s)
withFailure _ -> Nonelet() =
let strings = ["42"; "3.14"; "hello"; "123"; "45.67"] inList.iter (fun s ->
Printf.printf ""%s" -> int: %d, float: %f\n" s (string_to_int s) (string_to_float s)
) strings
Quick answerMake an HTTP GET request using Cohttp-lwt-unix or other HTTP clients.
GET: Cohttp_lwt_unix.Client.get
POST: Client.post
Headers: Header.init
JSON: Cohttp_lwt_body.of_string
Ocaml
# HTTPGET request
# UsingCohttp
# (Requires: opam install cohttp-lwt-unix)
openLwtopenCohttpopenCohttp_lwt_unixlet fetch_data url =
let uri = Uri.of_string url inClient.get uri >>= fun (response, body) ->
Body.to_string body >>= fun body_text ->
Lwt.return body_text
let fetch_data_sync url =
Lwt_main.run (fetch_data url)
let post_data url data =
let uri = Uri.of_string url inlet body = Cohttp_lwt_body.of_string data inClient.post uri ~body >>= fun (response, body) ->
Body.to_string body >>= fun body_text ->
Lwt.return body_text
let post_json url json_data =
let uri = Uri.of_string url inlet headers = Header.init_with "Content-Type""application/json"inlet body = Cohttp_lwt_body.of_string json_data inClient.post uri ~headers ~body >>= fun (response, body) ->
Body.to_string body >>= fun body_text ->
Lwt.return body_text
let() =
Printf.printf "HTTP examples available with Cohttp\n";
(* Example: *)(* let result = fetch_data_sync "https://api.github.com" in *)(* Printf.printf "%s\n" result *)
Quick answerCalculate factorial using recursion, iteration, or tail recursion.
Recursive: if n <= 1 then 1 else n * factorial (n-1)
Iterative: for i = 2 to n do result := !result * i
Tail recursive: helper acc n
Fold: List.fold_left (*) 1
Ocaml
# Factorialletrec factorial n =
if n <= 1then1else n * factorial (n - 1)
let factorial_iter n =
let result = ref1infor i = 2to n do
result := !result * i
done;
!result
let factorial_tail n =
letrec helper acc n =
if n <= 1then acc
else helper (acc * n) (n - 1)
in
helper 1 n
let factorial_fold n =
List.fold_left (*) 1 (List.init n (fun i -> i + 1))
let () =
let n = 5 in
Printf.printf "Factorial of %d:\n" n;
Printf.printf "Recursive: %d\n" (factorial n);
Printf.printf "Iterative: %d\n" (factorial_iter n);
Printf.printf "Tail recursive: %d\n" (factorial_tail n);
Printf.printf "Fold: %d\n" (factorial_fold n)
Quick answerCalculate Fibonacci numbers using recursion, iteration, or memoization.
Recursive: fib (n-1) + fib (n-2)
Iterative: for i = 2 to n do a, b = b, a + b
Tail recursive: helper a b i
Memoized: Hashtbl.find
Ocaml
# Fibonacciletrec fibonacci n =
if n <= 1then n
else fibonacci (n - 1) + fibonacci (n - 2)
let fibonacci_iter n =
if n <= 1then n
elselet a = ref0inlet b = ref1infor i = 2to n dolet c = !a + !b in
a := !b;
b := c
done;
!b
let fibonacci_tail n =
letrec helper a b i =
if i >= n then b
else helper b (a + b) (i + 1)
inif n <= 1then n
else helper 011let fibonacci_memo n =
let cache = Hashtbl.create 100inletrec fib n =
if n <= 1then n
elsetryHashtbl.find cache n
withNot_found ->
let result = fib (n - 1) + fib (n - 2) inHashtbl.add cache n result;
result
in
fib n
let() =
let n = 10inPrintf.printf "Fibonacci of %d:\n" n;
Printf.printf "Recursive: %d\n" (fibonacci n);
Printf.printf "Iterative: %d\n" (fibonacci_iter n);
Printf.printf "Tail recursive: %d\n" (fibonacci_tail n);
Printf.printf "Memoized: %d\n" (fibonacci_memo n)
Quick answerImplement FizzBuzz using pattern matching or if-else conditions.
If-else: if i mod 15 = 0 ...
Pattern matching: match (i mod 3, i mod 5) with
List: List.init n
Output: print_endline
Ocaml
# FizzBuzzlet fizzbuzz n =
for i = 1to n doif i mod15 = 0then print_endline "FizzBuzz"elseif i mod3 = 0then print_endline "Fizz"elseif i mod5 = 0then print_endline "Buzz"elsePrintf.printf "%d\n" i
donelet fizzbuzz_list n =
List.init n (fun i -> i + 1)
|> List.map (fun i ->
if i mod15 = 0then"FizzBuzz"elseif i mod3 = 0then"Fizz"elseif i mod5 = 0then"Buzz"else string_of_int i
)
let fizzbuzz_pattern n =
letrec helper i =
if i > n then()elselet result = match (i mod3, i mod5) with
| (0, 0) -> "FizzBuzz"
| (0, _) -> "Fizz"
| (_, 0) -> "Buzz"
| _ -> string_of_int i
in
print_endline result;
helper (i + 1)
in
helper 1let() =
Printf.printf "FizzBuzz for 15:\n";
fizzbuzz 15;
Printf.printf "FizzBuzz list:\n";
List.iter print_endline (fizzbuzz_list 15);
Printf.printf "FizzBuzz pattern:\n";
fizzbuzz_pattern 15
Quick answerFind missing number using sum formula or XOR operation.
Sum: total - sum
XOR: xor_all lxor xor_arr
Formula: n * (n + 1) / 2
Time: O(n)
Ocaml
# Find missing number
let find_missing arr =
let n = Array.length arr + 1inlet total = n * (n + 1) / 2inlet sum = Array.fold_left (+) 0 arr in
total - sum
let find_missing_list lst =
let n = List.length lst + 1inlet total = n * (n + 1) / 2inlet sum = List.fold_left (+) 0 lst in
total - sum
let find_missing_xor arr =
let n = Array.length arr + 1inlet xor_all = ref0infor i = 1to n do
xor_all := !xor_all lxor i
done;
let xor_arr = ref0inArray.iter (fun x -> xor_arr := !xor_arr lxor x) arr;
!xor_all lxor !xor_arr
let() =
let arr = [|1; 2; 4; 5; 6|] inPrintf.printf "Missing number: %d\n" (find_missing arr);
Printf.printf "Missing number (XOR): %d\n" (find_missing_xor arr);
let lst = [1; 2; 4; 5; 6] inPrintf.printf "Missing number (list): %d\n" (find_missing_list lst)
Quick answerImplement quick sort with pivot selection and partitioning.
Recursive: quick_sort = function
In-place: quick_sort_inplace arr low high
Pivot: Last element
Time: O(n log n) average
Ocaml
# Quick sort
letrec quick_sort = function
| [] -> []
| pivot :: rest ->
let left = List.filter (fun x -> x <= pivot) rest inlet right = List.filter (fun x -> x > pivot) rest in
quick_sort left @ [pivot] @ quick_sort right
let partition arr low high =
let pivot = arr.(high) inlet i = ref low infor j = low to high - 1doif arr.(j) <= pivot thenbeginlet temp = arr.(!i) in
arr.(!i) <- arr.(j);
arr.(j) <- temp;
i := !i + 1enddone;
let temp = arr.(!i) in
arr.(!i) <- arr.(high);
arr.(high) <- temp;
!i
letrec quick_sort_inplace arr low high =
if low < high thenlet pi = partition arr low high in
quick_sort_inplace arr low (pi - 1);
quick_sort_inplace arr (pi + 1) high
let quick_sort_array arr =
let result = Array.copy arr in
quick_sort_inplace result 0 (Array.length result - 1);
result
let quick_sort_optimized = function
| [] -> []
| pivot :: rest ->
let left = List.fold_left (fun acc x -> if x <= pivot then x :: acc else acc) [] rest inlet right = List.fold_left (fun acc x -> if x > pivot then x :: acc else acc) [] rest in
quick_sort_optimized left @ [pivot] @ quick_sort_optimized right
let() =
let lst = [5; 3; 8; 4; 2; 7; 1; 6] inlet arr = [|5; 3; 8; 4; 2; 7; 1; 6|] inPrintf.printf "Original: ";
List.iter (fun x -> Printf.printf "%d " x) lst;
print_endline "";
Printf.printf "Quick sort: ";
List.iter (fun x -> Printf.printf "%d " x) (quick_sort lst);
print_endline "";
Printf.printf "Quick sort (in-place): ";
Array.iter (fun x -> Printf.printf "%d " x) (quick_sort_array arr);
print_endline ""
Quick answerGroup records by a property using a hashtable for efficient grouping.
Hashtbl: Hashtbl.find and Hashtbl.replace
Key function: fun p -> p.age
Aggregation: group_and_sum
Time: O(n)
Ocaml
# Group by property
type person = {
name: string;
age: int;
city: string;
}
let group_by_property lst key =
let groups = Hashtbl.create 10inList.iter (fun item ->
let key_value = key item inifHashtbl.mem groups key_value thenlet current = Hashtbl.find groups key_value inHashtbl.replace groups key_value (item :: current)
elseHashtbl.add groups key_value [item]
) lst;
Hashtbl.fold (fun k v acc -> (k, List.rev v) :: acc) groups []let group_by_age persons =
group_by_property persons (fun p -> p.age)
let group_by_city persons =
group_by_property persons (fun p -> p.city)
let group_and_sum lst key value =
let groups = Hashtbl.create 10inList.iter (fun item ->
let key_value = key item inlet value_to_add = value item inifHashtbl.mem groups key_value thenlet current = Hashtbl.find groups key_value inHashtbl.replace groups key_value (current + value_to_add)
elseHashtbl.add groups key_value value_to_add
) lst;
Hashtbl.fold (fun k v acc -> (k, v) :: acc) groups []let() =
let people = [
{ name = "Alice"; age = 25; city = "NYC" };
{ name = "Bob"; age = 30; city = "LA" };
{ name = "Charlie"; age = 25; city = "NYC" };
{ name = "David"; age = 35; city = "Chicago" };
{ name = "Eve"; age = 30; city = "LA" };
] inPrintf.printf "Group by age:\n";
List.iter (fun (age, persons) ->
Printf.printf "Age %d: " age;
List.iter (fun p -> Printf.printf "%s " p.name) persons;
print_endline ""
) (group_by_age people);
Printf.printf "Group by city:\n";
List.iter (fun (city, persons) ->
Printf.printf "City %s: " city;
List.iter (fun p -> Printf.printf "%s " p.name) persons;
print_endline ""
) (group_by_city people)
Quick answerImplement pipe using fold or composition for function chaining.
Fold: List.fold_left (fun acc f -> f acc)
Operator: |>
Composition: compose
Direction: Left to right
Ocaml
# Pipefunctionlet pipe fns value =
List.fold_left (fun acc f -> f acc) value fns
let pipe_operator f g x = g (f x)
let (|>) x f = f x
let (<|) f x = f x
let compose f g x = f (g x)
let pipe_with_logging fns value =
letrec helper value = function
| [] -> value
| f :: rest ->
let result = f valueinPrintf.printf "Value: %s\n" (string_of_int result);
helper result rest
in
helper value fns
let() =
let double x = x * 2inlet add_ten x = x + 10inlet square x = x * x inlet result = pipe [double; add_ten; square] 5inPrintf.printf "Pipe: %d\n" result;
let result2 = 5 |> double |> add_ten |> square inPrintf.printf "Pipe operator: %d\n" result2;
let result3 = square (add_ten (double 5)) inPrintf.printf "Direct: %d\n" result3;
let composed = compose square (compose add_ten double) inPrintf.printf "Composed: %d\n" (composed 5)
Quick answerImplement compose using recursion or fold for function composition.
Fold: List.fold_left compose
Operator: >>, <<
Recursion: compose_list
Direction: Right to left
Ocaml
# Composefunctionlet compose f g x = f (g x)
let compose_list fns =
List.fold_left compose (fun x -> x) fns
let compose_right f g x = g (f x)
let compose_all fns x =
List.fold_right (fun f acc -> f acc) fns x
let pipe_operator f g x = g (f x)
let (>>) f g x = g (f x)
let (<<) f g x = f (g x)
let compose_with_logging fns =
letrec helper acc = function
| [] -> acc
| f :: rest ->
let composed = fun x ->
let result = f (acc x) inPrintf.printf "Result: %d\n" result;
result
in
helper composed rest
in
helper (fun x -> x) (List.rev fns)
let() =
let double x = x * 2inlet add_ten x = x + 10inlet square x = x * x inlet composed = compose square (compose add_ten double) inPrintf.printf "Composed: %d\n" (composed 5);
let composed2 = compose_list [double; add_ten; square] inPrintf.printf "Composed list: %d\n" (composed2 5);
let result = 5 |> double |> add_ten |> square inPrintf.printf "Pipe: %d\n" result;
let result2 = (double >> add_ten >> square) 5inPrintf.printf "Compose operator: %d\n" result2
Quick answerImplement memoization using a hashtable to cache function results.
Cache: Hashtbl.create
Check: Hashtbl.mem
Limit: memoize_with_limit
Multiple args: Tuple as key
Ocaml
# Memoizationlet memoize f =
let cache = Hashtbl.create 100infun x ->
ifHashtbl.mem cache x thenHashtbl.find cache x
elselet result = f x inHashtbl.add cache x result;
result
let memoize_fib =
letrec fib n =
if n <= 1then n
else fib (n - 1) + fib (n - 2)
in
memoize fib
let memoize_with_limit f limit =
let cache = Hashtbl.create 100inlet count = ref0infun x ->
if !count >= limit then
(Hashtbl.clear cache; count := 0);
ifHashtbl.mem cache x thenHashtbl.find cache x
elselet result = f x inHashtbl.add cache x result;
count := !count + 1;
result
let memoize_multiple f =
let cache = Hashtbl.create 100infun x y ->
let key = (x, y) inifHashtbl.mem cache key thenHashtbl.find cache key
elselet result = f x y inHashtbl.add cache key result;
result
let() =
let start = Unix.time ()inlet result1 = memoize_fib 35inlet time1 = Unix.time () -. start inlet start2 = Unix.time ()inlet result2 = memoize_fib 35inlet time2 = Unix.time () -. start2 inPrintf.printf "First: %d (%.6fs)\n" result1 time1;
Printf.printf "Second: %d (%.6fs)\n" result2 time2;
let add_memo = memoize_multiple (fun x y -> x + y) inPrintf.printf "Memoized add: %d\n" (add_memo 53);
Printf.printf "Memoized add (cached): %d\n" (add_memo 53)
Quick answerImplement once function that ensures a function is called only once.
Flag: called ref
Result: result ref option
Reset: once_with_reset
Async: once_async
Ocaml
# Oncefunctionlet once f =
let called = reffalseinlet result = refNoneinfun x ->
if not !called thenbegin
called := true;
result := Some (f x)
end;
match !result with
| Some v -> v
| None -> failwith "Unexpected None"let once_multiple f =
let called = reffalseinlet result = refNoneinfun args ->
if not !called thenbegin
called := true;
result := Some (f args)
end;
match !result with
| Some v -> v
| None -> failwith "Unexpected None"let once_with_reset f =
let called = reffalseinlet result = refNoneinlet reset () =
called := false;
result := Noneinlet fn x =
if not !called thenbegin
called := true;
result := Some (f x)
end;
match !result with
| Some v -> v
| None -> failwith "Unexpected None"in
(fn, reset)
let once_async f =
let called = reffalseinlet result = refNoneinlet promise = refNoneinfun x ->
if not !called thenbegin
called := true;
let p, r = Lwt.task ()in
promise := Some (p, r);
let _ = Lwt.async (fun() ->
letvalue = f x in
result := Somevalue;
Lwt.wakeup_exn (snd (Option.get !promise)) value;
Lwt.return ()
) in
fst (Option.get !promise)
endelsematch !result with
| Some v -> Lwt.return v
| None -> fst (Option.get !promise)
let() =
let initialize = once (fun x -> Printf.printf "Initialized with %d\n" x; x * 2) inPrintf.printf "First: %d\n" (initialize 10);
Printf.printf "Second: %d\n" (initialize 20);
let (fn, reset) = once_with_reset (fun x -> x * 2) inPrintf.printf "First with reset: %d\n" (fn 10);
reset ();
Printf.printf "After reset: %d\n" (fn 20)
Quick answerImplement debounce with leading edge using timer and last call time.
Timer: Thread.delay
State: last_call ref
Timeout: timeout ref option
Callback: debounce_leading_with_callback
Ocaml
# Debouncewith leading edge
let debounce_leading f delay =
let last_call = ref0.0inlet timeout = refNoneinfun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbegin
last_call := now;
f x
endelsematch !timeout with
| Some _ -> ()
| None ->
let _ = Thread.create (fun() ->
Thread.delay delay;
timeout := None;
last_call := Unix.time ();
f x
) ()in()let debounce_leading_with_callback f delay callback =
let last_call = ref0.0inlet timeout = refNoneinfun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbegin
last_call := now;
let result = f x in
callback result
endelsematch !timeout with
| Some _ -> ()
| None ->
let _ = Thread.create (fun() ->
Thread.delay delay;
timeout := None;
last_call := Unix.time ();
let result = f x in
callback result
) ()in()let debounce_leading_async f delay =
let last_call = ref0.0inlet timeout = refNoneinfun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbegin
last_call := now;
Lwt.return (f x)
endelsematch !timeout with
| Some _ -> Lwt.return ()
| None ->
let p, r = Lwt.task ()in
timeout := Some (p, r);
let _ = Lwt.async (fun() ->
Lwt_unix.sleep delay >>= fun() ->
timeout := None;
last_call := Unix.time ();
let result = f x inLwt.wakeup r result;
Lwt.return ()
) in
p
let() =
Printf.printf "Debounce examples available\n"
Quick answerImplement throttle with leading edge by checking time since last call.
State: last_call ref
Skipped: Track skipped calls
Trailing: throttle_with_trailing
Use case: Rate limiting
Ocaml
# Throttlewith leading edge
let throttle_leading f delay =
let last_call = ref0.0infun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbegin
last_call := now;
f x
endlet throttle_leading_with_skipped f delay =
let last_call = ref0.0inlet skipped = ref0infun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbeginif !skipped > 0thenbeginPrintf.printf "Skipped %d calls\n" !skipped;
skipped := 0end;
last_call := now;
f x
endelse
skipped := !skipped + 1let throttle_leading_async f delay =
let last_call = ref0.0infun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbegin
last_call := now;
Lwt.return (f x)
endelseLwt.return ()let throttle_with_trailing f delay =
let last_call = ref0.0inlet pending = refNoneinlet timer = refNoneinfun x ->
let now = Unix.time ()inif now -. !last_call >= delay thenbegin
last_call := now;
f x
endelsebegin
pending := Some x;
match !timer with
| Some _ -> ()
| None ->
let _ = Thread.create (fun() ->
Thread.delay delay;
timer := None;
last_call := Unix.time ();
match !pending with
| Somevalue -> f value
| None -> ()
) ()in()endlet() =
Printf.printf "Throttle examples available\n"
OCaml is a functional programming language from the ML family that combines functional, imperative, and object-oriented programming features with a powerful static type system.
What are the main features of OCaml?
OCaml features include functional programming, pattern matching, type inference, modules, functors, variants, records, polymorphism, garbage collection, and efficient native code compilation.
What is pattern matching in OCaml?
Pattern matching in OCaml is a powerful feature used to compare data structures and execute different code paths based on the structure of values.
What is type inference in OCaml?
Type inference in OCaml allows the compiler to automatically determine variable and function types without requiring explicit type declarations.
What are modules in OCaml?
Modules in OCaml are structures used to organize code, encapsulate data, and create reusable components with well-defined interfaces.
What are functors in OCaml?
Functors in OCaml are higher-order modules that take modules as input and generate new modules as output, enabling reusable and generic code design.
What are variants and records in OCaml?
Variants allow developers to define types with multiple possible forms, while records provide structured data types containing named fields.
How does recursion work in OCaml?
Recursion in OCaml allows functions to call themselves to solve problems by breaking them into smaller subproblems. It is commonly used in functional programming.
Why are OCaml interview questions important?
OCaml interview questions evaluate knowledge of functional programming, type systems, algorithms, recursion, modules, compiler concepts, and software design skills.
How can I prepare for an OCaml interview?
Practice OCaml syntax, functional programming concepts, pattern matching, recursion, modules, functors, type inference, polymorphism, data structures, and solve practical OCaml programming problems.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.