Re: Page 76 of OCaml by John Whitington ???
"Douglas Lewit [email protected] [ocaml_beginners]" <[email protected]> Mon, 28 Mar 2016 23:41:03 -0500
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <CAM0XMJQgCuZKAefu344nW03Og2uXtXTNWa-o-JBj_ztpMFTBDA@mail.gmail.com> |
I also gave something like this a try, but I ended up with a couple of error messages: *let pack list = match list with* *|[ ] -> [ ]* *|head :: tail -> match tail with* *|[ ] -> [ ]* *headOfTail :: tailOfTail -> if head = headOfTail then..... ( more code )* I thought it was clever, but either I just ended up with an empty list, a one-element list, or the compiler just rejected it. I'm starting to feel a little dumb! But I'll keep at it. On Mon, Mar 28, 2016 at 7:12 AM, Kenneth Miller [email protected] [ocaml_beginners] <[email protected]> wrote: > > > Right - almost always, if you're using references in a strongly typed > functional language, you're going against the idioms and best strengths of > the language. It can be hard to think of everything as having a recursive > solution, especially since it can often have non-obvious implementation > when you first start. Frequently, new functional programmers find > themselves repeating the habits they've been taught in imperative > languages, and those can be hard to unlearn. > > And thank you for your kind words! I'm honored, but I'm just an avid > learner with a master's; universities wouldn't accept me. I think I'll > pursue a PhD soon, but I have to finish my obligations with my current line > of work first. Also, Dr. Sleator's fix of your function clearly illustrates > what I've said above while also nudging you away from using references. > Thanks Dr. Sleator. > > > > On Sunday, March 27, 2016 10:21 PM, "[email protected] > [ocaml_beginners]" <[email protected]> wrote: > > > > Part of the problem is that the "reference solution" is incomprehensible. > Here's how I did it: > > let pack li = > let rec grab_block li ac = > (* Grab a block of equal elements from li and put them into ac. > Return the pair (li,ac). *) > match li with > | [] -> ([],ac) > | x::tail -> > if ac=[] || x = List.hd ac then grab_block tail (x::ac) > else (li, ac) > in > let rec loop li ac = if li = [] then List.rev ac else > let (rest,bl) = grab_block li [] in > loop rest (bl::ac) > in > loop li [] > > I think this is much easier to understand, and just as efficient. > > ---DS > > > >