Search⌘ K
AI Features

Programming Challenges

Explore programming challenges focusing on common functional patterns such as map, fold, and zip. Learn to implement functions to manipulate algebraic data types like either and binary trees, and to check sorted lists. Develop practical skills in applying higher-order functions for various computation tasks in OCaml.

Challenge 1: map on either type

The following algebraic datatype defines the either type:

type ('a, 'b) either = Left of 'a | Right of 'b

As a convention, Right of 'b holds the correct value while Left of 'a represents an error value.

Write a mapping function for either called map_either : ('a -> 'b) -> ('c, 'a) either -> ('c, 'b) either.

Examples:

map_either (fun x -> x * x) (Right 2)= Right 4
map_either (fun x -> x * x) (Left "Error case") = Left "Error case"
OCaml
(** [square x] returns the square of an input integer. *)
let square x = x * x
type ('a, 'b) either = Left of 'a | Right of 'b
(** [map_either f e] applies a function [f] to an either [e]. *)
let map_either f e = Left "TODO" (* TODO: Replace the hard-coded value with your code here *)

Challenge 2: fold_left

The ...