0% found this document useful (0 votes)
17 views12 pages

OCaml 2 Basics

The document provides a comprehensive overview of OCaml programming, covering key concepts such as recursion, user-defined data types, algebraic data types (ADTs), and higher-order functions. It includes detailed explanations, examples, and problems to test skills across various difficulty levels. Additionally, it offers practical functions for manipulating lists and handling user input.

Uploaded by

sinhasubhradip01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views12 pages

OCaml 2 Basics

The document provides a comprehensive overview of OCaml programming, covering key concepts such as recursion, user-defined data types, algebraic data types (ADTs), and higher-order functions. It includes detailed explanations, examples, and problems to test skills across various difficulty levels. Additionally, it offers practical functions for manipulating lists and handling user input.

Uploaded by

sinhasubhradip01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Basics of OCaml

Index

1. Recursion functions
a. Recursion (Definition, need of recursion, weaknesses, example)
b. Tail recursion (difference and advantages)
c. Mutual recursion (advantages)
2. User Defined data types
a. Variants
b. Records
c. type nats = Zero | Succ of nats
d. type num = A of int | B of float
3. ADTs
a. Algebraic Data type (Syntax, Definition, Examples, Need and advantages)
4. Functions for ADTs
a. Add function for nats
b. Convert function for nats (nats ->int)
c. Creating nats values (int ->. nats)
5. Reading inputs from the user
a. Read_int()
b. Raed_line()
6. Conditions (If-then-else)
a. Simple if else
b. Chained if else
c. Nested if else
7. Pattern Matching
a. Syntax
b. Advantages over if else
c. Advance pattern matching
8. Accessing Lists (using recursion)
a. Making list using recursion (make_list “hi” 3 -> [“hi”; “hi”; “hi”])
b. Count the number of elements
c. Take out 1st element
d. Take out last element
e. Take out both first and last element
9. Functions for lists (What they do, how to make it using recursion, how to use it)
a. List.map
b. List.nth
c. List.fold
d. List.filter
10. Higher order functions
a. Creating functions that take functions as input
b. Creating functions that return functions as output
11. Problems to test your skills
a. Basic problems
b. Medium problems
c. Hard problems
Basics of OCaml

1. Recursion Functions

a. Recursion (Definition, Need of Recursion, Weaknesses, Example)

• Definition: A function that calls itself within its definition to solve a problem by breaking it
into smaller sub-problems.

• Need: Useful for tasks like tree traversal, factorial calculation, and solving problems on lists.

• Weaknesses:

o Can lead to stack overflow if too deep.

o Less efficient unless optimized (e.g., tail recursion).

Example:

let rec factorial n =

if n = 0 then 1 else n * factorial (n - 1);;

b. Tail Recursion (Difference and Advantages)

• Difference: In tail recursion, the recursive call is the last operation.

• Advantages: Optimized by OCaml into iterative processes, preventing stack overflow.

Example:

let rec factorial_tail n acc =

if n = 0 then acc

else factorial_tail (n - 1) (n * acc);;

(* Usage: factorial_tail 5 1 *)

c. Mutual Recursion (Advantages)

• Definition: Two or more functions that call each other recursively.

• Advantages: Useful for state-dependent problems like alternating computations.

Example:

let rec is_even n =

if n = 0 then true else is_odd (n - 1)

and is_odd n =

if n = 0 then false else is_even (n - 1);;

2. User-Defined Data Types


a. Variants

Variants allow you to define a type with multiple possibilities.

type shape = Circle of float | Rectangle of float * float;;

b. Records

Records group related fields.

type person = { name: string; age: int };;

c. type nats = Zero | Succ of nats

Defines natural numbers recursively.

type nats = Zero | Succ of nats;;

d. type num = A of int | B of float

Defines a type that can hold either an integer or a float.

type num = A of int | B of float;;

3. ADTs (Algebraic Data Types)

a. Syntax, Definition, Examples, Need and Advantages

• Syntax: Combines types using | for sum types and records for product types.

• Definition: Combines multiple types into one type.

• Examples:

• type option = None | Some of 'a;;

• Need and Advantages:

o Simplifies modeling complex structures.

o Enables safe pattern matching.

4. Functions for ADTs

a. Add Function for nats

let rec add_nats n1 n2 =

match n1 with

| Zero -> n2

| Succ n -> Succ (add_nats n n2);;

b. Convert Function for nats (nats -> int)

let rec nats_to_int n =


match n with

| Zero -> 0

| Succ n -> 1 + nats_to_int n;;

c. Create nats Values (int -> nats)

let rec int_to_nats n =

if n = 0 then Zero else Succ (int_to_nats (n - 1));;

5. Reading Inputs from the User

a. read_int()

let n = read_int ();;

b. read_line()

let str = read_line ();;

6. Conditions (If-Then-Else)

a. Simple If-Else

let is_positive n = if n > 0 then "Positive" else "Non-positive";;

b. Chained If-Else

let classify n =

if n > 0 then "Positive"

else if n < 0 then "Negative"

else "Zero";;

c. Nested If-Else

let nested_check n =

if n > 0 then

if n mod 2 = 0 then "Positive Even" else "Positive Odd"

else "Not Positive";;

7. Pattern Matching

a. Syntax

match expr with

| pattern1 -> result1


| pattern2 -> result2

| _ -> default_result;;

b. Advantages Over If-Else

• Cleaner and more expressive.

• Safer and more exhaustive.

c. Advanced Pattern Matching

let describe_list lst =

match lst with

| [] -> "Empty list"

| [x] -> "Single-element list"

| x :: xs -> "Multiple-element list";;

8. Accessing Lists (Using Recursion)

a. Making a List Using Recursion

let rec make_list elem n =

if n = 0 then [] else elem :: make_list elem (n - 1);;

b. Count the Number of Elements

let rec count_elements lst =

match lst with

| [] -> 0

| _ :: xs -> 1 + count_elements xs;;

c. Take Out 1st Element

let first_elem lst = List.hd lst;;

d. Take Out Last Element

let rec last_elem lst =

match lst with

| [x] -> x

| _ :: xs -> last_elem xs;;

e. Take Out Both First and Last Element

let first_and_last lst = (List.hd lst, last_elem lst);;


9. Functions for Lists

a. List.map

let rec map f lst =

match lst with

| [] -> []

| x :: xs -> f x :: map f xs;;

b. List.nth

let rec nth lst n =

match lst with

| [] -> failwith "Index out of bounds"

| x :: xs -> if n = 0 then x else nth xs (n - 1);;

c. List.fold

let rec fold f acc lst =

match lst with

| [] -> acc

| x :: xs -> fold f (f acc x) xs;;

d. List.filter

let rec filter f lst =

match lst with

| [] -> []

| x :: xs -> if f x then x :: filter f xs else filter f xs;;

10. Higher Order Functions

a. Creating Functions That Take Functions as Input

let apply_twice f x = f (f x);;

b. Creating Functions That Return Functions as Output

let add_n n = (fun x -> x + n);;

11. Problems to Test Your Skills

a. Basic Problems

1. Compute factorial using tail recursion.


2. Check if a list is empty.

3. Write a function to reverse a list.

4. Count occurrences of an element in a list.

5. Create a function to double all elements in a list.

b. Medium Problems

1. Implement a binary search tree and a function to search it.

2. Write a function to merge two sorted lists.

3. Find all permutations of a list.

4. Write a function to check if a list is a palindrome.

5. Generate Fibonacci sequence up to n terms.

c. Hard Problems

1. Create a binary tree and implement inorder traversal.

2. Write a function to solve the Tower of Hanoi problem.

3. Write a function to evaluate expressions using pattern matching.

4. Implement quicksort using recursion.

5. Implement a simple interpreter for arithmetic expressions.

Would you like a deeper dive into any specific topic or problem?

------The End----

Continue for solutions…


Source: chatGPT :p

Solving All the Problems with Explanations

11. Problems to Test Your Skills

a. Basic Problems

1. Compute Factorial Using Tail Recursion


Explanation: Use an accumulator to hold the result during recursion.

let rec factorial_tail n acc =

if n = 0 then acc

else factorial_tail (n - 1) (n * acc);;

(* Usage: factorial_tail 5 1 *)

2. Check if a List is Empty


Explanation: Use pattern matching to check the list structure.

let is_empty lst =

match lst with

| [] -> true

| _ -> false;;

3. Write a Function to Reverse a List


Explanation: Accumulate reversed elements in a helper function.

let reverse lst =

let rec aux acc lst =

match lst with

| [] -> acc

| x :: xs -> aux (x :: acc) xs

in aux [] lst;;

4. Count Occurrences of an Element in a List


Explanation: Recursively traverse the list and increment a counter when matching elements
are found.

let rec count_occurrences elem lst =

match lst with

| [] -> 0
| x :: xs -> (if x = elem then 1 else 0) + count_occurrences elem xs;;

5. Create a Function to Double All Elements in a List


Explanation: Use List.map or recursion to double each element.

let rec double_elements lst =

match lst with

| [] -> []

| x :: xs -> (2 * x) :: double_elements xs;;

b. Medium Problems

1. Implement a Binary Search Tree and Search It


Explanation: Define a binary tree and recursive search function.

type bst =

| Empty

| Node of int * bst * bst;;

let rec search_bst x tree =

match tree with

| Empty -> false

| Node (v, left, right) ->

if x = v then true

else if x < v then search_bst x left

else search_bst x right;;

2. Merge Two Sorted Lists


Explanation: Use recursion to merge while maintaining order.

let rec merge_sorted l1 l2 =

match (l1, l2) with

| [], l | l, [] -> l

| x1 :: xs1, x2 :: xs2 ->

if x1 < x2 then x1 :: merge_sorted xs1 l2

else x2 :: merge_sorted l1 xs2;;

3. Find All Permutations of a List


Explanation: Use recursion to build permutations.
let rec insert_at x lst i =

match (lst, i) with

| l, 0 -> x :: l

| [], _ -> failwith "Index out of bounds"

| y :: ys, _ -> y :: insert_at x ys (i - 1);;

let rec permutations lst =

match lst with

| [] -> [[]]

| x :: xs ->

List.concat (

List.mapi (fun i p -> insert_at x p i) (permutations xs)

);;

4. Check if a List is a Palindrome


Explanation: Reverse the list and compare it to the original.

let is_palindrome lst =

lst = List.rev lst;;

5. Generate Fibonacci Sequence up to n Terms


Explanation: Use recursion to compute terms.

let rec fibonacci n =

if n = 0 then 0

else if n = 1 then 1

else fibonacci (n - 1) + fibonacci (n - 2);;

let rec fib_sequence n =

if n = 0 then []

else fib_sequence (n - 1) @ [fibonacci (n - 1)];;

c. Hard Problems

1. Binary Tree and Inorder Traversal


Explanation: Visit the left subtree, root, and right subtree.

type btree =
| Empty

| Node of int * btree * btree;;

let rec inorder tree =

match tree with

| Empty -> []

| Node (v, left, right) -> inorder left @ [v] @ inorder right;;

2. Tower of Hanoi Problem


Explanation: Move disks between rods recursively.

let rec tower_of_hanoi n source aux target =

if n = 1 then [(source, target)]

else

tower_of_hanoi (n - 1) source target aux

@ [(source, target)]

@ tower_of_hanoi (n - 1) aux source target;;

3. Evaluate Expressions Using Pattern Matching


Explanation: Use variants to represent expressions.

type expr =

| Num of int

| Add of expr * expr

| Mul of expr * expr;;

let rec eval e =

match e with

| Num n -> n

| Add (e1, e2) -> eval e1 + eval e2

| Mul (e1, e2) -> eval e1 * eval e2;;

4. Implement Quicksort Using Recursion


Explanation: Partition the list and sort each part recursively.

let rec quicksort lst =

match lst with

| [] -> []
| pivot :: rest ->

let left = List.filter (fun x -> x <= pivot) rest

and right = List.filter (fun x -> x > pivot) rest in

quicksort left @ [pivot] @ quicksort right;;

5. Simple Interpreter for Arithmetic Expressions


Explanation: Parse strings into expressions and evaluate them.

type expr =

| Num of int

| Add of expr * expr

| Sub of expr * expr

| Mul of expr * expr

| Div of expr * expr;;

let rec eval e =

match e with

| Num n -> n

| Add (e1, e2) -> eval e1 + eval e2

| Sub (e1, e2) -> eval e1 - eval e2

| Mul (e1, e2) -> eval e1 * eval e2

| Div (e1, e2) -> eval e1 / eval e2;;

Would you like further explanation or test cases for any specific problem?

You might also like