Skip to search.

Breaking News Visit Yahoo! News for the latest.

×Close this window

ocaml_beginners · Ocaml Beginners

The Yahoo! Groups Product Blog

Check it out!

Group Information

? Already a member? Sign in to Yahoo!

Yahoo! Groups Tips

Did you know...
Real people. Real stories. See how Yahoo! Groups impacts members worldwide.

Messages

Advanced
Messages Help
Messages 7188 - 7217 of 13887   Oldest  |  < Older  |  Newer >  |  Newest
Messages: Show Message Summaries Sort by Date ^  
#7188 From: code17 <code17@...>
Date: Thu Feb 1, 2007 9:38 am
Subject: Re: module rec
code_1977
Send Email Send Email
 
Then I guess there is no other solution other than recursive module, because
it's actually recursive: Mod1 and Mod2 depends my_struct and hence must see
state_t, while the module State where state_t should be defined in also
depends on Mod1 and Mod2.

Unless you can try to factor out the parts in Mod1 and Mod2 on which State
depends and move them into State, but it really depends.

Good luck!

- code17

dmitry grebeniuk <gds-mlsts@...> writes:
> I want the compiler to check my code, because it really
> guarantees that state_t can be created/modified only in one
> small module. This module can be fully and quickly checked
> without reviewing other parts of my code.
>
> I don't need the cool feature "private type", I could be
> satisfied by opaque state_t, but I can't declare it as
> opaque type because of the structure of my code, described
> in previous letter (functions that work with state_t
> requires some functions that work with my_struct).

#7189 From: "roparzhhemon" <roparzhhemon@...>
Date: Sat Feb 3, 2007 2:53 pm
Subject: ocamlmktop trouble : .cmo file remembers more than it should
roparzhhemon
Send Email Send Email
 
Hello all,

   let me describe a ocamlmktop-specific compilation problem that I encountered :
I have two modules, let's call them  A and B, that are completely unrelated (in
the sense
that the contents of the file a.ml does not contain any
reference "B." to the module B,  the .depend file created with
ocamldep indicates that a.ml is not a dependency for b.cmo,
and vice versa). But the following sequence of actions causes trouble :

    (*starting from an "up-to-date" make, with all .cmo's files created without
error or warning *)

   1) Changing the implementation of the module A (in down-to-earth terms,
changing the contents of a.ml)
  2) Recompiling with make (essentially a sequence of "ocamlc -c" actions
applied to a.ml and other modules that depend on A)

  So far,so good. At this point, I thus have new  "a.cmo&a.cmi" files  and  old
"b.cmi&b.cmo" files.

  3) If I try to create my custom toplevel from all the .cmo files with
ocamlmktop,
I get the error message

   "Files a.cmo and b.cmo make inconsistent assumptions over interface A
    make : *** [toplevel] Error 2"

   So it seems that the old b.cmo file remembers things about the
a.cmi file, even though the two modules are unrelated. I can get around
the problem by using a "make clean" and recompiling everything from
scratch, but that's definitely unsatisfying ...
    Has anyone else experienced a similar problem ? Any suggestions ?
Thank in advance.

                                                                                      
Ewan

#7190 From: Christian Lerrahn <ocaml@...>
Date: Mon Feb 5, 2007 4:15 am
Subject: Formatting float in string_of_float
js.fan
Send Email Send Email
 
Hi,
is it possible to specify a format for floats in string_of_float. E.g.
could I say that I want 5 decimals or e.g. an xxe+/-yy notation like
1.56e23? I know that I can do that with fprintf or sprintf but is it
also possible in string_of_float?

Cheers,
Christian

#7191 From: Martin Jambon <martin_jambon@...>
Date: Mon Feb 5, 2007 6:02 am
Subject: Re: "ocaml_beginners"::[] Formatting float in string_of_float
BioMim
Send Email Send Email
 
On Mon, 5 Feb 2007, Christian Lerrahn wrote:

> Hi,
> is it possible to specify a format for floats in string_of_float. E.g.
> could I say that I want 5 decimals or e.g. an xxe+/-yy notation like
> 1.56e23? I know that I can do that with fprintf or sprintf but is it
> also possible in string_of_float?

No. What's wrong with sprintf?


--
Martin Jambon
http://martin.jambon.free.fr

#7192 From: Christian Lerrahn <ocaml@...>
Date: Mon Feb 5, 2007 10:37 am
Subject: Re: "ocaml_beginners"::[] Formatting float in string_of_float
js.fan
Send Email Send Email
 
Am Sun, 4 Feb 2007 22:02:15 -0800 (PST)
schrieb Martin Jambon <martin_jambon@...>:

> On Mon, 5 Feb 2007, Christian Lerrahn wrote:
>
> > Hi,
> > is it possible to specify a format for floats in string_of_float.
> > E.g. could I say that I want 5 decimals or e.g. an xxe+/-yy
> > notation like 1.56e23? I know that I can do that with fprintf or
> > sprintf but is it also possible in string_of_float?
>
> No. What's wrong with sprintf?

I thought sprintf was not type safe whereas string_of_float was but I
found out that sprintf seems to be type safe as well. So I really don't
need string_of_float.

Cheers,
Christian

#7193 From: dmitry grebeniuk <gds-mlsts@...>
Date: Mon Feb 5, 2007 1:24 pm
Subject: Printf: takes "format", does nothing.
dmitrygrebeniuk
Send Email Send Email
 
Shalom.

   I want to make a function that takes argument of type
"('a, 'b, 'c) format" (or "... format4"), all following
arguments, and silently ignores them all, returning unit
value.
   Simple approach doesn't work:

========================================
value (nothingf : format 'a 'b 'c -> unit) _fmt = ()
;

value () = nothingf "%i %c" 123 'a'
;
========================================

$ ocamlopt -w A -pp camlp4r tst.ml -o tst.exe
File "tst.ml", line 4, characters 11-19:
This function is applied to too many arguments,
maybe you forgot a `;'
mingw32-make.exe: *** [tst.exe] Error 2

   Why I need it?  I want to create a function that prints
debug messages, so that the function was either
(Printf.fprintf logfile "myformat" myargs) or
(nothingf "myformat" myargs) depending on some boolean
value (for example, "do_write_debug_info : bool").

   Now I have the following code (application is
windows-specific, for unix there will be "/dev/null"
instead of "NUL"):

value do_write_debug_info = False
;

value debug_info_filename =
   if do_write_debug_info
   then "debug.log"
   else "NUL"
;

value debug_info_channel = open_out debug_info_filename
;

value (dbg : format 'a out_channel unit -> 'a) fmt =
   Printf.fprintf debug_info_channel fmt
;

value () = dbg "%i %c" 123 'a'
;

   But I think that it's a bit ugly and sometimes slow to
make all formatting just for sending it to /dev/null.

--
WBR,
  dmitry                          mailto:gds-mlsts@...

#7194 From: "roparzhhemon" <roparzhhemon@...>
Date: Mon Feb 5, 2007 2:58 pm
Subject: (*) is not multiplication
roparzhhemon
Send Email Send Email
 
Hello all,

         According to the latest (3.09) Objective Caml manual, (*) is
the multiplication function int->int->int, just like (+) or
(/). My toplevel begs to differ :

   d212-96-69-170:~ ewan$ ocaml
         Objective Caml version 3.09.3

# (+);;
- : int -> int -> int = <fun>
# (/);;
- : int -> int -> int = <fun>
# (*);;
Warning C: this is the start of a comment.
*

                            Is it an error in the manual, or am I using the wrong
"*"
character (or encoding ?) on my Mac ?

                                                                     Ewan

#7195 From: Michael DiBernardo <mikedebo@...>
Date: Mon Feb 5, 2007 3:07 pm
Subject: Re: "ocaml_beginners"::[] (*) is not multiplication
mikedebo_ca
Send Email Send Email
 
Just put a space between the asterisk and the parens:

# ( * );;
- : int -> int -> int = <fun>

   Debo

On 5-Feb-07, at 6:58 AM, roparzhhemon wrote:

>
>
> Hello all,
>
> According to the latest (3.09) Objective Caml manual, (*) is
> the multiplication function int->int->int, just like (+) or
> (/). My toplevel begs to differ :
>
> d212-96-69-170:~ ewan$ ocaml
> Objective Caml version 3.09.3
>
> # (+);;
> - : int -> int -> int = <fun>
> # (/);;
> - : int -> int -> int = <fun>
> # (*);;
> Warning C: this is the start of a comment.
> *
>
> Is it an error in the manual, or am I using the wrong "*"
> character (or encoding ?) on my Mac ?
>
> Ewan
>
>
>



[Non-text portions of this message have been removed]

#7196 From: Jon Harrop <jon@...>
Date: Mon Feb 5, 2007 3:03 pm
Subject: Re: "ocaml_beginners"::[] (*) is not multiplication
harropjon
Send Email Send Email
 
On Monday 05 February 2007 14:58, roparzhhemon wrote:
>                   Hello all,
>
>         According to the latest (3.09) Objective Caml manual, (*) is
> the multiplication function int->int->int, just like (+) or
> (/). My toplevel begs to differ :
>
>   d212-96-69-170:~ ewan$ ocaml
>         Objective Caml version 3.09.3
>
> # (+);;
> - : int -> int -> int = <fun>
> # (/);;
> - : int -> int -> int = <fun>
> # (*);;
> Warning C: this is the start of a comment.
> *
>
>                            Is it an error in the manual, or am I using the
> wrong "*" character (or encoding ?) on my Mac ?

You must put spaces to disambiguate:

   ( * )

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
OCaml for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists

#7197 From: code17 <code17@...>
Date: Mon Feb 5, 2007 3:13 pm
Subject: Re: (*) is not multiplication
code_1977
Send Email Send Email
 
This is due to the syntactic ambiguity, since comment in OCaml also begins
with "(*". Extra spacing will help it recognize.

# ( * );;
- : int -> int -> int = <fun>
# (  *  );;
- : int -> int -> int = <fun>

"roparzhhemon" <roparzhhemon@...> writes:
> # (*);;
> Warning C: this is the start of a comment.
> *

#7198 From: micha <micha-1@...>
Date: Mon Feb 5, 2007 3:09 pm
Subject: Re: "ocaml_beginners"::[] (*) is not multiplication
scheischeischei
Send Email Send Email
 
you need to write it with a space:

( * )

cheers,
  Michael

> .

#7199 From: Martin Jambon <martin_jambon@...>
Date: Mon Feb 5, 2007 6:52 pm
Subject: Re: "ocaml_beginners"::[] Formatting float in string_of_float
BioMim
Send Email Send Email
 
On Mon, 5 Feb 2007, Christian Lerrahn wrote:

> Am Sun, 4 Feb 2007 22:02:15 -0800 (PST)
> schrieb Martin Jambon <martin_jambon@...>:
>
> > On Mon, 5 Feb 2007, Christian Lerrahn wrote:
> >
> > > Hi,
> > > is it possible to specify a format for floats in string_of_float.
> > > E.g. could I say that I want 5 decimals or e.g. an xxe+/-yy
> > > notation like 1.56e23? I know that I can do that with fprintf or
> > > sprintf but is it also possible in string_of_float?
> >
> > No. What's wrong with sprintf?
>
> I thought sprintf was not type safe whereas string_of_float was but I
> found out that sprintf seems to be type safe as well. So I really don't
> need string_of_float.

The only dangerous thing with the printf functions is that partial
applications used to not work as expected, but it's not the case anymore.

If I recall correctly, before you would get:

# let f = Printf.printf "Hello %s";;
Helloval f : string -> unit = <fun>
# f "x";;
x- : unit = ()

... which was always surprising.


But in ocaml 3.09.3 (I don't know since when exactly but this is
documented somewhere) you get:

# let f = Printf.printf "Hello %s";;
val f : string -> unit = <fun>
# f "x";;
Hello x- : unit = ()

That's nicer.


Martin

--
Martin Jambon
http://martin.jambon.free.fr

#7200 From: "mtthfntn" <mtthfntn@...>
Date: Mon Feb 5, 2007 7:58 pm
Subject: Re: OCaml and multi-core processors
mtthfntn
Send Email Send Email
 
Hi,

I believe I have good news for you. The Ocaml team is very aware of
the issue but because they have said that concurrent GC is out of
question for now and have not even expressed interest for STM, both
topics being regularly brought up on the Ocaml lists, people jump to
wrong conclusions like the following comments on this thread from
known Ocaml lists addicts ;-)
"I don't believe the guys at INRIA are addressing the parallelism of
OCaml"
"Until someone discovers a way to do parallel garbage collection for
free, and a suitable way to write threaded code sensibly is also
discovered (mutexes and shared memory is _not_ a sane way to write
code), INRIA have made it quite clear they're not interested."

The reality is that the Ocaml developers don't discuss their roadmap
EVER (easy to understand why) which leaves us with browsing CVS as the
only way to infer their plans by looking at their activity. And the
CVS logs reveal they are working very actively to come up with a
distributed/concurrent evolution of Ocaml. Now to the good news:

1) The language is called OcamlP3l (actually it's the second
incarnation of it, having been re(de)fined and rewritten entirely)
2) It's a FANTASTIC answer to the distribution/concurrency problem
3) It's already totally usable (well at least testable, let's wait for
the Ocaml team to let us know when they themselves consider it usable).

You can download it here http://ocamlp3l.inria.fr

I urge everyone on this thread to read the manual's introduction here:
http://ocamlp3l.inria.fr/UserManual.htm#htoc1 in the hope it will blow
your mind as much as it did mine.

And it's beyond fun to try :-)))

--- In ocaml_beginners@yahoogroups.com, "Eric Berend"
<tradewisdom@...> wrote:
>
> Hi,
>
>     After a careful evaluation process, candidate languages for a
> proposed financial markets analysis programming project have been
> narrowed down to a very short list that includes OCaml. Many computer
> languages were considered in selecting the best fit, and OCaml appears
> to be have the most optimal combination of necessary qualities and
> features; however, with one important exception: no threading
> capability, as the executables compiled in OCaml are *non* re-entrant
> in the x86 architecture.
>
>     Upon reading into development history of the language, it became
> apparent that some of the team in charge of design, deliberately
> avoided enabling this feature. While I am not a fan of Intel, and
> agreed with the viewpoint that Hyper-threading was virtual
> 'smoke-and-mirrors' in many respects, the effect at this point, today,
>  has been to become left out of the current trend of advancement of
> processing power through increasing CPU core counts rather than
> increasing processor clock speeds.
>
>     This one problem has completely impeded adoption of OCaml as the
> development language of choice for this project. Much as I have often
> loathed the actions of Microsoft in our industry, their "F#" variant
> *does* allow re-entrant code. What are the designers and development
> personnel at INRIA involved in the OCaml project, doing to address
> this issue? Ours cannot be the only endeavor with such considerations.
>
>     Thank you for your time and consideration in answering about this
> concern.
>
>
>     Sincerely,
>
>     Eric Berend
>

#7201 From: Francois Colonna <colonna@...>
Date: Fri Feb 9, 2007 3:32 pm
Subject: string argument of failwith has a limited length.
colonna_fran...
Send Email Send Email
 
Hello

It seems that the string argument of failwith has a limited length.
Where is this documented ?

Thanks
Francois Colonna

#7202 From: Virgile Prevosto <virgile.prevosto@...>
Date: Fri Feb 9, 2007 3:44 pm
Subject: Re: "ocaml_beginners"::[] string argument of failwith has a limited length.
virgilepr
Send Email Send Email
 
Hello,

Le ven 09 fév 2007 16:32:14 CET,
Francois Colonna <colonna@...> a écrit :

> Hello
>
> It seems that the string argument of failwith has a limited length.
> Where is this documented ?

All ocaml strings have a limited length (namely Sys.max_string_size as
its name suggests), but you can pass such a string to failwith:

         Objective Caml version 3.09.3

# let s = String.make  Sys.max_string_length 'a';;
val s : string = <huge string>
# failwith s;;
Exception: Failure <huge string>.

--
E tutto per oggi, a la prossima volta.
Virgile

#7203 From: Dawid Toton <d0@...>
Date: Fri Feb 9, 2007 5:22 pm
Subject: rend & recv in threads
dawidtoton
Send Email Send Email
 
I have one connected socket and two threads.
1. thread should wait for data, do recv and process the result as soon
as any data is available
2. thread should write to the socket indeoendently

Unfortunateky it turned out that send & recv behave as if they are
protected with one mutex per one socket (I've checked it with
Unix.send/recv and ThreadUnix.send/recv - no difference). It happens
like this:

thread 1: send "blah"  (OK)
thread 2: recv         (returned "bloh" - sill OK)
thread 2: recv         (waiting for more data - OK)
thread 1: send "blah"  (waits for release of the socket - this is bad
for me)

Normally I would use two semaphores and a function waiting for multiple
objects:

let betterRecv sync1 sync2 sock buf offs =
  (
   while
    desiredFunctionWaitFor [sync1,sock] = TheFirstObjectWasSignaled
   do mySemaphore.wait sync2 done;
   recv sock buf offs []
  );;

let betterSend sync1 sync2 sock buf offs =
  (
   mySemaphore.Signal sync1;
   let result = send sock buf offs [] in
   (mySemaphore.Signal sync2;
    result
   )
  );

The problem is: I need to do it in a portable way.

Windows implementation of Unix.select doesn't allow waiting on any
primitives other than socket descriptors. Unix unit seems not to have
any "multipleWait" function that would be more general.

I tried such a nasty workaround:

(* we have no Unix.socketpair on Windows *)
let socketpair_workaround a b c =
  let sock1 = socket PF_INET SOCK_STREAM 0 in
  let addr1 = ADDR_INET (inet_addr_of_string "127.0.0.1",56291) in
  let sock2 = socket PF_INET SOCK_STREAM 0 in
(* let addr2 = ADDR_INET (inet_addr_of_string "127.0.0.1",56292) in*)
  bind sock1 addr1;
(* bind sock2 addr2;*)
  listen sock1 1;
  connect sock2 addr1;
  sock1, sock2
  ;;

let goodSend sync = send sync "d" 0 1 []; send;;
let goodRecv sync sock =
  (
   print_endline "-> select";
   while
     let readyS = (Unix.select [sock; sync] [] [] (-1.)) in
     match readyS with
     | [sync],_,_ -> print_endline "sync!" ; recv sync "?" 0 1 []; true
     | _,_,_ -> false
    do () done;
   let result = recv sock in
   let _ = print_endline "received" in
   result
  );;

which I tried to use like this:
let (syncOut,syncIn) = socketpair_workaround ...
... goodSend syncOut...  and in another thread: ... goodRecv syncIn...

But I haven't managed to make it work really (tested it on Windows).

My last stopgap mock-up was:

let goodRecv sock =
  (
   while
     let readyS = (Unix.select [sock] [] [] (0.1)) in
     match readyS with
     | [],_,_ -> Thread.delay 0.1; true
     | _,_,_ -> false
    do () done;
   recv sock
  );;

It is the only working version I have. But it is like an active waiting.
How should I do this in a proper way?

Thank you in advance for any help.

Dawid Toton

#7204 From: "fabrice.marchant" <fabrice.marchant@...>
Date: Fri Feb 9, 2007 10:32 pm
Subject: How to reuse code ?
fabrice.marc...
Send Email Send Email
 
Hi OCaml programmers !

   Coming from C++ beginner, I try to forget - for a time - oo use and
to focus on modules.

   I hope to reuse "show_array" code :

let show_array the_array print_function =
   Array.iteri (fun i x -> print_int i; print_char '\t';
                           print_function x; print_char '\n')
               the_array

let show_complex c = print_char '(' ;
                      print_float c.Complex.re ; print_string ",\t";
                      print_float c.Complex.im; print_char ')'

let () = show_array a_complex_array show_complex;
          show_array (Array.map Complex.norm a_complex_array)
                     print_float

   Maybe it would be possible to mimic C++ and to forge a base class
for show_array parameter : deriving a complex and simple float from it.

   But please, how to avoid to explicitly pass the print function to
"show_array" without using the oo features of OCaml ?

   Thanks for your help.

   Fabrice.
--
   I wonder if these naughty spammers that attack Caml-list these days
use "polygen" with a slightly modified grammar from "pornsite.grm" ?

#7205 From: Karl Zilles <zilles@...>
Date: Fri Feb 9, 2007 10:58 pm
Subject: Re: "ocaml_beginners"::[] How to reuse code ?
kzilles
Send Email Send Email
 
fabrice.marchant wrote:
> But please, how to avoid to explicitly pass the print function to
> "show_array" without using the oo features of OCaml ?

If you had a library of functions that all worked on a given type, you
could use functors.  But for a single function, passing the printer as a
parameter is exactly what you'd do.  Then you can use partial evaluation
to make it look nice:

let a_complex_array  = [|Complex.zero; Complex.one|]

(* note that print_array takes two parameters through we're only
declaring one explicitly *)

let print_array print_function =
      Array.iteri (fun i x ->
          print_int i;
          print_char '\t';
          print_function x;
          print_char '\n')

let print_complex c =
      print_char '(' ;
      print_float c.Complex.re;
      print_string ",\t";
      print_float c.Complex.im;
      print_char ')'

let print_complex_array = print_array print_complex
let print_float_array = print_array print_float

let () =
      print_complex_array a_complex_array;
      print_float_array (Array.map Complex.norm a_complex_array)

If, however, you're trying to write a generic function to dump generic
ocaml datastructures, the problem is much harder, since ocaml doesn't
keep type information with the variables.  There has been some useful
code posted to this list that does a good job for what it has to work with.

#7206 From: Martin Jambon <martin_jambon@...>
Date: Fri Feb 9, 2007 11:21 pm
Subject: Re: "ocaml_beginners"::[] How to reuse code ?
BioMim
Send Email Send Email
 
On Fri, 9 Feb 2007, fabrice.marchant wrote:

>  Hi OCaml programmers !
>
>  Coming from C++ beginner, I try to forget - for a time - oo use and
> to focus on modules.

Hi,

You really should use the printf family of functions from the Printf
module or from the Format module.

>  I hope to reuse "show_array" code :
>
> let show_array the_array print_function =
>  Array.iteri (fun i x -> print_int i; print_char '\t';
>                          print_function x; print_char '\n')
>              the_array

Here is what I would write:

open Printf

let show_array oc f a =
    Array.iteri (fun i x -> fprintf oc "%i\t%a\n" i f x) a


oc is the out_channel, which you can set to stdout if you want.
The order of the arguments of show_array and of f are such that they can
be used with fprintf or printf.

If you need pretty-printing, you can use the Format module. It's a bit
more complicated though. However it's more polymorphic since the output is
performed to an abstract formatter, which may be write to a channel or a
character buffer, rather than only out_channels.


> let show_complex c = print_char '(' ;
>                     print_float c.Complex.re ; print_string ",\t";
>                     print_float c.Complex.im; print_char ')'

let show_complex oc c =
    fprintf oc "(%10.6f,%10.6f)" c.Complex.re c.Complex.im

Note that I remove the tabs, which are almost always a bad solution.


> let () = show_array a_complex_array show_complex;
>         show_array (Array.map Complex.norm a_complex_array)
>                    print_float

let () =
    show_array stdout show_complex a_complex_array;
    show_array stdout
      (fun oc x -> fprintf oc "%10.6f" x)
      (Array.map Complex.norm a_complex_array);;


>  Maybe it would be possible to mimic C++ and to forge a base class
> for show_array parameter : deriving a complex and simple float from it.
>
>  But please, how to avoid to explicitly pass the print function to
> "show_array" without using the oo features of OCaml ?

let print_array = show_array stdout print_function


Martin

--
Martin Jambon
http://martin.jambon.free.fr

#7207 From: Fabrice Marchant <fabrice.marchant@...>
Date: Sat Feb 10, 2007 3:25 pm
Subject: Re: "ocaml_beginners"::[] How to reuse code ?
fabrice.marc...
Send Email Send Email
 
Karl and Martin, thanks !

I'll remember about "partial evaluation" :
> let print_complex_array = print_array print_complex

> ...to write a generic function to dump generic
> ocaml datastructures, the problem is much harder, since ocaml doesn't
> keep type information with the variables.  There has been some useful
> code posted to this list that does a good job for what it has to work
> with.

   I'm very interested in reading such previous topics. Maybe I have to search
"generic" word ? Please Karl, do you have other clues that could help to
locate them ?

> Here is what I would write:
>
> open Printf
>
> let show_array oc f a =
>    Array.iteri (fun i x -> fprintf oc "%i\t%a\n" i f x) a

Thanks, Martin ! Even for a newbie, it's a shame for me to have missed this
mandatory C-like lib...

> >  But please, how to avoid to explicitly pass the print function to
> > "show_array" without using the oo features of OCaml ?
>
> let print_array = show_array stdout print_function
  If I understand this, Martin : a kind of partial evaluation,
the thing Karl spoke about ?

   Regards

  Fabrice

#7208 From: Jon Harrop <jon@...>
Date: Sat Feb 10, 2007 3:52 pm
Subject: Re: "ocaml_beginners"::[] How to reuse code ?
harropjon
Send Email Send Email
 
On Saturday 10 February 2007 15:25, Fabrice Marchant wrote:
>   I'm very interested in reading such previous topics. Maybe I have to
> search "generic" word ? Please Karl, do you have other clues that could
> help to locate them ?

Basically, whenever you define or use a type that you're going to want to be
able to convert into string format, you write a string_of_foo function. For
example:

# type pos = {x: int; y:int};;

# let string_of_pos r = Printf.sprintf "(%d, %d)" r.x r.y;;
val string_of_pos : pos -> string = <fun>

If you have a polymorphic type then your string_of_foo function is a
higher-order function that expects the appropriate string_of_* function for
the type parameter. For example, a string_of_list function will accept a
string_of_elt function to convert each element into a string:

# let string_of_list string_of_elt list =
     "["^String.concat "; " (List.map string_of_elt list)^"]";;
val string_of_list : ('a -> string) -> 'a list -> string = <fun>

These design patterns in OCaml are covered in my book "OCaml for Scientists".

> > Here is what I would write:
> >
> > open Printf
> >
> > let show_array oc f a =
> >    Array.iteri (fun i x -> fprintf oc "%i\t%a\n" i f x) a
>
> Thanks, Martin ! Even for a newbie, it's a shame for me to have missed this
> mandatory C-like lib...

I believe there is a thorough discussion in the OCaml manual. Also, fire up
the ocamlbrowser program and look at the documentation for the Printf module.

> > >  But please, how to avoid to explicitly pass the print function to
> > > "show_array" without using the oo features of OCaml ?
> >
> > let print_array = show_array stdout print_function
>
>  If I understand this, Martin : a kind of partial evaluation,
> the thing Karl spoke about ?

Exactly. All function definitions are curried by default in OCaml. So when you
write a function that tries to find an element in a list:

# let rec find f list = match list with
   | [] -> raise Not_found
   | h::t when f h -> h
   | _::t -> find f t;;
val find : ('a -> bool) -> 'a list -> 'a = <fun>

you can partially apply the "find" function with a function "f" to search for
particular elements. For example, you can create a function to find only even
elements in an int list:

# let find_even = find (fun i -> i mod 2 = 0);;
val find_even : int list -> int = <fun>

Currying makes for concise code. However, you can get into problems if you try
to mix currying, outer-most definitions and polymorphism.

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
OCaml for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists

#7209 From: "jshaw10" <jshaw10@...>
Date: Sat Feb 10, 2007 10:20 pm
Subject: Re: rend & recv in threads
jshaw10
Send Email Send Email
 
Howdy!

I've run into this exact problem. One solution is to compile your
program using the cygwin environment, which will give caml a POSIX
environment under windows.

http://cygwin.com/

This works quite well for some cases. Other than that, your readyS
function is about the only thing that I can think of.

#7210 From: Martin Jambon <martin_jambon@...>
Date: Sun Feb 11, 2007 3:50 am
Subject: Re: "ocaml_beginners"::[] How to reuse code ?
BioMim
Send Email Send Email
 
On Sat, 10 Feb 2007, Fabrice Marchant wrote:

>>>  But please, how to avoid to explicitly pass the print function to
>>> "show_array" without using the oo features of OCaml ?
>>
>> let print_array = show_array stdout print_function
> If I understand this, Martin : a kind of partial evaluation,
> the thing Karl spoke about ?

Yes. However the term "partial application" is more appropriate than
"partial evaluation", because it doesn't do anything with the body of the
function (show_array) until all the arguments are passed.

Consider this:

let f x y =
    let z = x * x in
    x + y

let g = f 2

g is internally organized as a record containing a pointer to the function
(f) and the arguments that have been given already (x = 2).
z is *not* computed when you create g.

It constrasts with:

let f x =
    let z = x * x in
    fun y -> x + y



Martin

--
Martin Jambon
http://martin.jambon.free.fr

#7211 From: Fabrice Marchant <fabrice.marchant@...>
Date: Sun Feb 11, 2007 12:15 pm
Subject: Re: "ocaml_beginners"::[] How to reuse code ?
fabrice.marc...
Send Email Send Email
 
Thank you, John and Martin for the explanations and the examples of partial
functions ! They are very useful for me.

> "... covered in my book "OCaml for Scientists"
John, I would be glad to buy your book if only I could find it in France.
(But last time I imported something from States - it was a DDJ CD, 8 years ago
-, Federal Express claimed then heavy additional taxes or fees that were hidden
before...)

   Martin, the two contrasting examples you give encourage to be very cautious
about OCaml coding : for a same job, I bet the execution speed can be different.

   The following example seems to be closely related to the things you explain.
I wanted a function to handle graphics init and exit for a drawing function :

let graphic_main drawing_fun =
   open_graph " 800x600";
   drawing_fun ();
   set_color foreground;
   moveto 0 0; draw_string "'Q' to quit.";
   let keep = ref true in
   while !keep do
     let e = wait_next_event [Key_pressed] in
       if e.keypressed then(
         match e.key with
         | 'q' | 'Q' -> keep := false
         | _         -> ()
       )
   done;
   close_graph()

which was written with a zero parameter function "drawing_fun" in mind.

I was then surprised it was possible to use "graphic_main" with multi parameters
functions in adding a dummy one this way :

let three_true_parms_draw_something p1 p2 p3 dum =...

let () = graphic_main (three_true_parm_draws_something 1 2 3)

It compiles and works. However this last parameter seems rather tricky...

  Best regards

   Fabrice

#7212 From: "drehman27" <drehman27@...>
Date: Sun Feb 11, 2007 4:07 pm
Subject: Programming Contest: How well can you play 'Continuo'?
drehman27
Send Email Send Email
 
Hi,

The LISPers threw a programming contest for the upcoming International
Lisp Conference (ILC 2007) in Cambridge U.K.

The contest is a cute card game called "Continuo", and the rules are here:
http://www.international-lisp-conference.org/2007/contest

The contest is for LISP only, but I am posting it here, in case other
OCamlers are interested in this interesting game.
As an exercise, I wrote a Common Lisp program and then translated it
to OCaml.

- Dário

#7213 From: "fabrice.marchant" <fabrice.marchant@...>
Date: Sun Feb 11, 2007 4:41 pm
Subject: Another OCaml vs C
fabrice.marc...
Send Email Send Email
 
Hi !

   In order to learn OCaml, I begin to program toy applications.
For example : the knight that runs one times on each square of the
chess board.

Here is the complete program : ( Apologize to exhibit such a naughty
thing : it's my 2nd OCaml program. Good thing to have a beginner list... )
http://fabrice.marchant.free.fr/OCaml/knight/one/

The heart is :

...
   let b = new board width height in
   let d = new display width height box_n in
   let rec solve s =
     if b#is_free s then(
       b#set s;
       if b#full () then
         b#print d;
       List.iter (fun c -> let target =(s ++ c) in
                             if b#own target then
                               solve target)
                 delta;
       b#free s
     )

The C program p. 10, Fig 16 of :
http://perso.orange.fr/jean-paul.davalan/graphs/cours/graphes.pdf

  It works exactly the same way :

void next(int n, int x, int y) { /* position suivante */

   int k, X, Y;

   quad[x][y] =n;
   if( n<NN ) {
     for( k =0; k<8; ++k ) {
       X =x + DIF[k][0],
       Y =y + DIF[k][1];
       if( X>=0 && X<N && Y>=0 && Y<N && quad[X][Y]==0 )
         next( n+1, X, Y );
     }
   } else if( n==NN ) { /* affichage de la solution */
     ++num;
     if( !quiet || num<=1 )
       solution();
   }
   quad[x][y] =0;
}

   However, ( after restricting OCaml pgm to (0, 0) start square - to
compare same jobs ), the C program appears to be about 10 times speeder.
   I thought C/OCaml speed ratio was smaller, say about 2 or 3. But maybe
something goes wrong with my program.

   Moreover, I rewrote the program and use ocamlgraph lib :
http://fabrice.marchant.free.fr/OCaml/knight/two/

  - building first the graph of knight possible moves in order to avoid
later tests about to be or not inside the board
  - then looking for a hamiltonian path of the graph

Unfortunately, the speed results are even worst...

If you know an example of a speed well written chess knight OCaml
program somewhere, I would be interested.

Regards

Fabrice

#7214 From: "Remi Vanicat" <remi.vanicat@...>
Date: Sun Feb 11, 2007 6:06 pm
Subject: Re: "ocaml_beginners"::[] Another OCaml vs C
dl_ens
Send Email Send Email
 
2007/2/11, fabrice.marchant <fabrice.marchant@...>:
[...]
>   let b = new board width height in
>   let d = new display width height box_n in
[...]
>
>   However, ( after restricting OCaml pgm to (0, 0) start square - to
> compare same jobs ), the C program appears to be about 10 times speeder.
>   I thought C/OCaml speed ratio was smaller, say about 2 or 3. But maybe
> something goes wrong with my program.

You fell in the object trap : objects are slower in ocaml than the
rest of the language, and not so useful. rewrite your code in plain
caml (with object), compile it ocamlopt, and you will have more
similar result, with one catch : ocaml array bound are by default
checked at each access, will C array are not, then f you want speed
over safety, you can compile with the -unsafe option of the compiler.

#7215 From: "fabrice.marchant" <fabrice.marchant@...>
Date: Mon Feb 12, 2007 10:00 am
Subject: Re: Another OCaml vs C
fabrice.marc...
Send Email Send Email
 
Thanks Remi !

> You fell in the object trap : objects are slower in ocaml than the
> rest of the language, and not so useful. rewrite your code in
plain

I remember that John Harrop's warned me about this.

As soon as I fix my debian system that is down today, I rewrite the
program in nonO-Caml.

   Regards

#7216 From: "Grant Olson" <olsongt@...>
Date: Tue Feb 13, 2007 9:45 pm
Subject: Is ocaml smart on memory usage here?
olsongt@...
Send Email Send Email
 
I've got some rather large records that contain a bunch of OpenGL vertex
information.  These also have associated textures.  Sometimes these get
're-skinned' where I replace the OpenGL textures with something like:

{md3 with surfaces=new_surfaces}

Quick spot checking of the memory seems to be okay, but I just wanted to
confirm if this copy operation is or isn't copying the contents of other
immutable fields within the record, in particular the extremely large vertex
data that is maintained in a different field.  I can change my approach if
it is.

Thanks,

Grant

#7217 From: "Remi Vanicat" <remi.vanicat@...>
Date: Tue Feb 13, 2007 10:05 pm
Subject: Re: "ocaml_beginners"::[] Is ocaml smart on memory usage here?
dl_ens
Send Email Send Email
 
2007/2/13, Grant Olson <olsongt@...>:
> I've got some rather large records that contain a bunch of OpenGL vertex
> information.  These also have associated textures.  Sometimes these get
> 're-skinned' where I replace the OpenGL textures with something like:
>
> {md3 with surfaces=new_surfaces}
>
> Quick spot checking of the memory seems to be okay, but I just wanted to
> confirm if this copy operation is or isn't copying the contents of other
> immutable fields within the record, in particular the extremely large vertex
> data that is maintained in a different field.  I can change my approach if
> it is.

the {md3 with surfaces=new_surfaces} contruct make a copy of the old
md3. Then all a record really contain in the "C" meaning of contain,
is integer and pointer. So your extremely large data is not copied,
only the pointer to it is.

Messages 7188 - 7217 of 13887   Oldest  |  < Older  |  Newer >  |  Newest
Add to My Yahoo!      XML What's This?

Copyright © 2010 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Guidelines NEW - Help