OCaml
(* sqsum *) let rec sqsum0 xs = if xs = [] then 0 else (List.hd xs * List.hd xs) + sqsum0 (List.tl xs) ;; let rec sqsum1 xs = match xs with | [] -> 0 | e::r -> e*e + sqsum1 r ;; let rec sqsum2 = function | [] -> 0 | e::r -> e*e + sqsum1 r ;; let sqsum3 xs = List.fold_left (fun acc x -> acc + x) 0 (List.map (fun x -> x*x) xs) ;; let sqsum4 = List.fold_left (fun acc x -> acc + x*x) 0 ;; let sqsum5 xs = let rec parcours ys som = match ys with | [] -> som | e::r -> parcours r (e*e + som) in parcours xs 0 ;; (* et si la liste est vide ?.... On peut créer une exception*) let sqsum6 xs = let rec parcours ys som = match ys with | [] -> failwith "Liste vide : somme impossible !" | e::[] -> e | e::r -> parcours r (e*e + som) in parcours xs 0 ;; (* moyenne *) let somme0 xs = let rec parcours ys som = match ys with | [] -> som | e::r -> parcours r (e + som) in parcours xs 0 ;; let rec somme1 xs = match xs with | [] -> 0 | e::r -> e + somme1 r ;; let rec somme2 = function | [] -> 0 | e::r -> e + somme1 r ;; let rec somme3 = function | [] -> failwith "Liste vide : somme impossible !" | e::[] -> e | e::r -> e + somme1 r ;; let somme4 = List.fold_left (+) 0 ;; let longueur0 xs = let rec parcours ys long = match ys with | [] -> long | _::r -> parcours r (1 + long) in parcours xs 0 ;; let rec longueur1 xs = match xs with | [] -> 0 | _::r -> 1 + longueur1 r ;; let longueur2 = List.fold_left (fun acc _ -> acc + 1) 0 ;; let pliage op neutre xs = let rec parcours ys acc = match ys with | [] -> acc | e::r -> parcours r (op acc e) in parcours xs neutre ;; let somme5 = pliage (fun acc x -> acc + x) 0 ;; let longueur3 = pliage (fun acc _ -> 1 + acc) 0 ;; let moyenne1 xs = float_of_int (somme3 xs) /. float_of_int (longueur3 xs) ;; let moyenne2 xs = let (som, long) = List.fold_left (fun (som, nb) x -> (som + x, nb + 1)) (0, 0) xs in float_of_int som /. float_of_int long ;; let moyenne3 xs = let rec parcours ys som long = match ys with | [] -> float_of_int som /. float_of_int long | e::r -> parcours r (som + e) (long + 1) in parcours xs 0 0 ;; (* et bien d'autres façons encore + gestion des exceptions *) (* ajout_trie *) let rec ajout_trie1 x xs = match xs with | [] -> [x] | e::r -> if x < e then x :: e :: r else e :: (ajout_trie1 x r) ;; let rec ajout_trie2 x xs = match xs with | [] -> [x] | e :: _ when x < e -> x::xs | e :: r -> e :: (ajout_trie2 x r) ;; let rec ajout_trie3 x xs = match xs with | [] -> [x] | e :: r when x = e -> xs | e :: r when x < e -> x:: xs | e :: r -> e :: (ajout_trie3 x r) ;; (* palindrome *) let rev1 xs = let rec transvase depart arrivee = match depart with | [] -> arrivee | e::r -> transvase r (e::arrivee) in transvase xs [] ;; let colle_a acc un_el = un_el :: acc ;; let rev2 = List.fold_left colle_a [] ;; let palin xs = xs = rev2 xs ;;