Functional Programming & Proofs

Exercices 1

  1. How to define a dictionary and use it to translate a text ?
    2.1 Split text
let txt ="I am a teacher";;
let lst = Seq.toList txt;;

let rec takeWhile xs = 
 match xs with 
 | [] -> []
 | v::vs -> if v<>' ' then v::(takeWhile vs) else [];;
takeWhile lst;;

let rec dropWhile xs = 
 match xs with 
 | [] -> []
 | v::vs -> if v<>' ' then (dropWhile vs) else vs;;
dropWhile lst;;

let rec split xs = 
 match xs with
 | [] -> []
 | vs -> (takeWhile vs)::( split (dropWhile vs));;
split lst;; // [['I']; ['a'; 'm']; ['a']; ['t'; 'e'; 'a'; 'c'; 'h'; 'e'; 'r']]

2.2 Define dictionary

let dic = ["I","Je";"teacher","enseignant";"am","suis"];;
let dic2= List.map (fun (x,y)->(Seq.toList x,Seq.toList y)) dic;;

let rec equ xs ys =
 match xs,ys with
 | [],[] -> true
 | _, [] -> false
 | [], _ -> false
 | v::vs,w::ws -> (v=w) && (equ vs ws);;
printfn "%b" (equ ['a'; 'm'] ['a'; 'm']);;

let rec has key dic = 
 match dic with
 | [] -> false
 | (k,v)::vs -> (equ k key) || (has key vs);;
printfn "%b" (has ['a','m'] dic2);;
let rec find key dic = // ?