Browse thread
[Caml-list] newbie questions
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Wolfgang Lux <wlux@u...> |
| Subject: | Re: [Caml-list] newbie questions |
Ruediger M.Flaig wrote: > 1.: Is there any means of doing list-type pattern matching (style "| > h::t -> ...") for recursion on strings? OK., I have realized that not > having a decent string type is one of the reason why programs in > Haskell or Erlang are much slower than in CAML, and resorted to a > "roll-your-own" for dealing with this: > > let ht x = (String.sub x 1 ((String.length x)-1)), String.make 1 > (compl x.[0]);; > > because I think that > > let compl = function 'g' -> 'c' | 'c' -> 'g' | 'a' -> 't' | 't' -> 'a' > | _ -> ' ';; > let rec complement = function > "" -> "" > | dna -> let h, t = ht dna in (complement h) ^ t;; > > is much smarter than the iterative version > > let compl = function 'g' -> 'c' | 'c' -> 'g' | 'a' -> 't' | 't' -> 'a' > | _ -> ' ';; > let complement dna = > let cdna = ref "" in > for i = 0 to String.length( dna )-1 do > let cha = String.get dna i in > cdna := (String.make 1 (compl cha)) ^ !cdna > done; > !cdna;; > > (Yes! Confess guilty! Learned Pascal in 1986...) > > but -- and this is my point -- there should certainly be some more > elegant way of dealing with this than the horrible "ht" definition, > shouldn't it? Actually, in many cases you would not want to implement such recursions yourself. Many recursion patterns can implemented by using the standard higher order functions unit, map, fold, etc. For instance, your complement function should be as simple as let complement dna = String.map compl dna To my surprise, the String module doesn't provide a map function (it does implement iter, though). If you were using an algebraic data type type Base = A | C | G | T you could make use of arrays and the implement complement using Array.map. Wolfgang ------------------- To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ Beginner's list: http://groups.yahoo.com/group/ocaml_beginners