jeudi 25 avril 2019

Getting a random number in a function in OCAML OR Telling compiler to evaluate function each time

I'm new to OCAML and was playing around with putting a marker on a random 5X5 square. I've written the example program below. "silly_method1" works but notice that it takes an argument. I don't really have argument to pass in for what I want. I'm just asking for a random number to create my robot on a particular square:

let create = {x = ( Random.int 4); y=3; face = North}

However, I get the same location each time. This makes sense to me... sort of. I'm assuming that the way I've set it up, "create" is basically a constant. It's evaluated once and that's it! I've fixed it below in silly_method2 but look how ugly it is!

let silly_method2 _ = (Random.int 10)

Every time I have to call it, I have to pass in an argument even though I'm not really using it.

What is the correct way to do this? There must be some way to have a function that takes no arguments and passes back a random number (or random tuple, etc.) And possibly related... Is there a way to tell OCaml not to evaluate the function once and save the result but rather recalculate the answer each time?

Thank you for your patience with me!

Dave

let _ = Random.self_init()

let silly_method1 x = x + (Random.int 10)
let silly_method2 _ = (Random.int 10)
let report1 x = (print_newline(); print_string("report1 begin:  "); print_int (silly_method1 x); print_string("report1 end"); print_newline(); )
let report2 y = (print_newline(); print_string("report2 begin:  "); print_int(silly_method2 y ); print_string("report2 end"); print_newline(); )

let _ = report1 3
let _ = report1 3
let _ = report1 3

let _ = report2 3
let _ = report2 3
let _ = report2 3




Aucun commentaire:

Enregistrer un commentaire