Computer Science Canada

Code snippet: using O'Caml for quick tasks

Author:  wtd [ Thu Jul 17, 2008 12:44 am ]
Post subject:  Code snippet: using O'Caml for quick tasks

I needed to quickly manipulate some data today, and the following ensued..

code:
# let lenses = [14, 2.8; 21, 3.2; 31, 1.8; 35, 2.; 35, 2.8; 40, 2.8; 43, 1.9; 50, 1.4; 55, 1.4; 70, 2.4; 77, 1.8; 85, 1.4];;
val lenses : (int * float) list =
  [(14, 2.8); (21, 3.2); (31, 1.8); (35, 2.); (35, 2.8); (40, 2.8);
   (43, 1.9); (50, 1.4); (55, 1.4); (70, 2.4); (77, 1.8); (85, 1.4)]
# let equivs = List.map (fun (l, a) -> Printf.sprintf "%0.0f f%0.1f" (float_of_int l *. 1.53) a) lenses;;
val equivs : string list =
  ["21 f2.8"; "32 f3.2"; "47 f1.8"; "54 f2.0"; "54 f2.8"; "61 f2.8";
   "66 f1.9"; "77 f1.4"; "84 f1.4"; "107 f2.4"; "118 f1.8"; "130 f1.4"]
# print_endline (List.fold_left (fun a b -> a ^ ", " ^ b) (List.hd equivs) (List.tl equivs));;
21 f2.8, 32 f3.2, 47 f1.8, 54 f2.0, 54 f2.8, 61 f2.8, 66 f1.9, 77 f1.4, 84 f1.4, 107 f2.4, 118 f1.8, 130 f1.4
- : unit = ()
#

Author:  Prabhakar Ragde [ Thu Jul 17, 2008 9:28 am ]
Post subject:  Re: Code snippet: using O'Caml for quick tasks

Just for the fun of it, I did this in PLT Scheme v4.0.2, Module language, using your intermediate variables:

code:

#lang scheme
(require srfi/48) ;; for fixed-width numeric formatting
(define lenses '((14 2.8) (21 3.2) (31 1.8) (35 2.0) (35 2.8) (40 2.8) (43 1.9) (50 1.4) (55 1.4) (70 2.4) (77 1.8) (85 1.4)))
(define equivs (map (lambda (x) (s:format "~1F f~1,1F" (rationalize (* 153/100 (first x)) 1) (second x))) lenses))
(display (first equivs))
(for-each (lambda (x) (printf ", ~a" x)) (rest equivs))


I thought for-each was a little clearer than foldl. --PR

Author:  wtd [ Fri May 12, 2023 2:51 pm ]
Post subject:  RE:Code snippet: using O\'Caml for quick tasks

With the benefit of time:

code:

# print_endline
  @@ String.concat ", "
  @@ Fun.flip List.map lenses
  @@ fun (f, a) -> Printf.sprintf "%d f%0.1f" f a;;
14 f2.8, 21 f3.2, 31 f1.8, 35 f2.0, 35 f2.8, 40 f2.8, 43 f1.9, 50 f1.4, 55 f1.4, 70 f2.4, 77 f1.8, 85 f1.4
- : unit = ()


Or:

code:

# lenses
  |> List.map (fun (f, a) -> Printf.sprintf "%d f%0.1f" f a)
  |> String.concat ", "
  |> print_endline;;
14 f2.8, 21 f3.2, 31 f1.8, 35 f2.0, 35 f2.8, 40 f2.8, 43 f1.9, 50 f1.4, 55 f1.4, 70 f2.4, 77 f1.8, 85 f1.4
- : unit = ()


: