small coding

Job ID: 33977042

Budget: $10 – $30 USD

Introduction to Lab Assignment 4
This assignment has you work with trees in F#.

Due: End of lab
Deliverables: Commit and push to Github. Submit to Gradescope
Part A: Practice with options
Part A.1 tryNth
tryNth takes in an index n and a list l. This function returns the item at the specified index, if available. However, if the list is shorter than n, you need to return None

> tryNth 0 [11]
Some 11
> tryNth 2 [11; 12]
None
> tryNth 0 []
None
Part A.2: tryFindIdx
This function takes in a predicate and a list. It searches through the list, and finds the index (wrapped inside an option) of the first element that satisfies the predicate (returns true). If there is no such element, return None.

> tryFindIdx (fun x -> x > 0) [-3; 0; 7]
Some 2
> tryFindIdx (fun x -> x > 0) [-3; 0; -7]
None
Part B: Practice with trees
Part B.1 toList
This function takes in a tree t, and converts it into a list. The elements are added to the list in in-order traversal (meaning the left subtree is added first, then the node itself, the right subtree). For example, the following tree

3
/ \
1 6
\
9
should return the list [1; 3; 6; 9]

Part B.2 count
This function counts how many elements in a tree satisfy the said predicate. For example, if t contained the above tree from B.1,

> count (fun x -> x > 0) t
4
> count (fun x -> x > 5) t
2
> count (fun x -> x > 10) t
0

Code skeleton:


module LA4 =

/// TODO: Complete and document
/// To be done without the List module.
let rec tryNth n l =
None

/// TODO: Complete and document
/// To be done without the List module.
let rec tryFindIdx pred l =
None

/// <summary>This type represents a binary tree. A binary tree can either be
/// - An empty node
/// - An inner node that also contains data
/// </summary>
type BinaryTree<'a> =
| Empty
| Node of BinaryTree<'a> * 'a * BinaryTree<'a>

let rec toList t =
[]

let rec count pred (t: BinaryTree<'a>) =
0

Unit tests if needed let me know:
Related categories: Programming F#