Soundex/OCaml: Difference between revisions

278 bytes removed ,  10 months ago
no edit summary
(a soundex version that can switch the language)
 
No edit summary
 
(One intermediate revision by one other user not shown)
Line 1:
Here is a version with very few changes, which allows choosing different languages ('''en''' for English, '''fr''' for French) of type '''lang''', the definition of this type will be hidden in the interface.
 
<lang ocaml>typesyntaxhighlight lang = char -"ocaml"> string
type lang = char -> string
 
let en = function
Line 49 ⟶ 50:
match dbl [] (List.rev !cl) with
| c::rem -> (String.make 1 c) ^ (soundex_aux lang rem)
| [] -> invalid_arg "soundex"</lang>
</syntaxhighlight>
 
We provide an additional function to create new lang parameters from simple data set:
 
<lang ocaml>type lang_set = (int * char list) list
 
let make_lang ss =
let ss = List.map (fun (d, li) -> string_of_int d, li) ss in
let ss = List.map (fun (d, li) -> List.map (fun c -> c, d) li) ss in
let ss = List.flatten ss in
(fun c -> try List.assoc c ss with Not_found -> "")</lang>
 
in the interface as the definition of the type '''lang''' is hidden we can use it easily as a classic parameter:
 
<syntaxhighlight lang ="ocaml">type lang
type lang
 
val en : lang
Line 71 ⟶ 64:
 
type lang_set = (int * char list) list
val make_lang : lang_set -> lang</lang>
</syntaxhighlight>
 
The '''lang''' parameter for the '''soundex''' function is optional, if omited the english set is used.
Line 81 ⟶ 75:
Test that the function make_lang provide the same results:
 
<syntaxhighlight lang ="ocaml">open Soundex
open Soundex
 
let tests = [
Line 109 ⟶ 104:
let status = if code1 = code2 then "OK " else "Arg" in
Printf.printf " \"%s\" \t %s %s %s\n" word code1 code2 status
) tests</lang>
</syntaxhighlight>
 
We can run this test file with: <code>ocaml soundex.cmo test.ml</code>
ocaml soundex.cmo test.ml