I'm making a sudoku game with in OCaml with the Graphics library.
I'm trying to add a timer at the top so that the player can see how long he's taking to solve the sudoku. I've looked around and the Lwt library seems to be what I'm looking for.
To draw the timer I wrote a function draw_time, the content of the function is too long and not important, but it has this kind of structure:
let rec hello () =
Lwt.bind (Lwt_unix.sleep 14400.)
(fun () -> print_endline "Hello, world !"; hello ())
Lwt.async (hello)
I've tested it and the function does work as it's supposed to.
The main loop of my game looks like this:
let main_loop gs f_init f_end f_key f_mouse =
f_init;
let timer = draw_time () in
try
while true do
try
if gs.completed <> true then
let event = Graphics.wait_next_event event_types in
if event.Graphics.keypressed then
f_key event.Graphics.key
else if event.Graphics.button then
f_mouse event.Graphics.mouse_x event.Graphics.mouse_y
with
| _ -> raise End
done
with
| End -> f_end ()
;;
This doesn't seem to work. The program only executes draw_time when I close the window (and the program) and not when the window is open and the timer is supposed to be drawn.
What am I doing wrong exactly?
In order to run Lwt program, you need to start the main loop, that will process your threads,
let () = Lwt_main.run (Lwt_io.printl "Hello, world!")
Lwt has code that will integrate Lwt main loop into the Glib. But, as far as I know, there is no such integration for Graphics module.
You may find async_graphics interesting, it is an integration of the Async library, that is quite near to Lwt with Graphics module. It was even mentioned in Real World OCaml
Related
I want to list every function of a SML library. Is there something like an help command?
For example:
Is there a way to see this list in the PolyML terminal?
I need to view it on the terminal without using google. I can't use internet during the exam and I can't bring notes.
You can type open TextIO; in the REPL. This will import the content of the module into your current scope, but in the REPL it will also have the side-effect of printing what it imported. You may not be interested in the scope being updated like that, so it may be wise to restart the REPL afterwards if you intend to use it again.
$ poly
Poly/ML 5.7.1 Release
> open TextIO;
structure StreamIO: TEXT_STREAM_IO
val canInput = fn: instream * int -> int option
val closeIn = fn: instream -> unit
val closeOut = fn: outstream -> unit
...
I'm trying to learn how to use the SDL libraries with OCaml, but I'm running into problems with handling keyboard input.
Specifically, I'm trying to understand how to use Sdlkey.get_key_state, which has a signature like this:
val get_key_state : unit ->
(int, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t
Essentially, I want to use the method outlined in this lazy foo tutorial. In C, it would look like this:
Uint8 *keystates = SDL_GetKeyState( NULL );
//If up is pressed
if( keystates[ SDLK_UP ] )
{
printf( "Up was pressed" );
}
Using the keystate array, you can check to see if each relevant key is being pressed. The alternate way of doing this is to poll for a key press event, and in OCaml it can be identified using pattern matching, for example:
let handleEvent ev =
match ev with
| Sdlevent.KEYDOWN {Sdlevent.keysym=Sdlkey.KEY_ESCAPE} -> exit 0
| _ -> ()
let mainLoop () =
while true do
begin match Sdlevent.poll () with
| None -> ()
| Some ev -> handleEvent ev
end;
done
I've seen several examples that illustrate this method, but I can't find any information on how to read the values returned from Sdlkey.get_key_state. I'm fairly new to functional programming, so this is a bit over my head. Can someone show me how to rewrite the C code above in OCaml?
Thanks
I don't know ocamlsdl (though I've used SDL before). But it might be good enough just to point out that OCaml big arrays are like C arrays, there's nothing particularly "functional" about them.
The nomenclature for the Bigarray module is quite thick, but what you're seeing is that get_key_state returns a one-dimensional array of unsigned 8-bit values, laid out the way that C lays out arrays. You can access an array element with the (not particularly pretty) notation a.{index}.
So the OCaml equivalent might look like this:
let keystates = get_key_state () in
if keystates.{KEY_UP} <> 0 then
(* Up key was pressed *)
One thing missing here is that I don't know exactly how to get the index KEY_UP. But it's probably explained in the docs for ocamlsdl.
I am writing a lwt-based Twitter API library and I want to implement the Twitter API's cursor functionality using Lwt_stream library.
I decide to use Lwt_stream.from and supply this function an argument f.
Here is what I currently do
let get_follower ~access_token ~screen_name ?(count=5000) ?(wait=true) () =
let base_uri = "https://api.twitter.com/1.1/followers/ids.json" in
let cursor = ref (-1) in
let f () =
Client.do_get_request
~uri_parameters:
["screen_name", screen_name;
"cursor", (string_of_int (!cursor));
"count", (string_of_int count)]
~uri:(Uri.of_string base_uri)
~access_token:access_token
() >>= fun res ->
match res with
| Ok (header, str) -> begin
match (Yojson.Safe.from_string str |> user_ids_of_yojson) with
| `Ok uids ->
cursor := uids.next_cursor;
return (Some (Ok uids))
| `Error msg -> failwith msg
end
| Error e -> return (Some (Error (process_error_exn e))) in
Lwt_stream.from f
I am not sure if I should use ref. The reason I use ref is that the behavior of f depends on the value it returns previously. To be specific, the value of cursor which will be used next time depends on current next_cursor, and if cursor is zero, f knows it reaches the end and returns None.
Is using ref here considered a good design choice? Is there any better way to implement this functionality?
Antron gave an excellent answer to my opinion, but I would like just to share with few practical advice. If I were you, I wouldn't use one big function named f with a ref, well, mostly because it smells, and it is quite unreadable and doesn't scale. I would create a stream using Lwt_stream.create and work with it using a recursive function, that do the main loop, with all the logic separated in helper functions. The main loop function can have state with which it recurs, so that we don't need ugly references or explicit mutability.
So, below is an example, of how your code can be restructured. I also didn't find an explicit check for a zero cursor, that should be used to stop the stream (as you mentioned in text), so I added this. Otherwise the code should work as yours.
So, I've split it into three functions: make_request is responsible for making the request. parse_response is a pure transformation, that deconstructs the answer. And finally, loop function performs the main loop, makes requests, parses them and stops on zero.
Note: looks like that you're using Or_error monad and mixing it with exceptions. This is a bad idea, since it breaks precondition, that a well formed function that returns Or_error.t should never throw exception.
let get_follower ~access_token ~screen_name ?(count=5000) ?(wait=true) () =
let base_uri = "https://api.twitter.com/1.1/followers/ids.json" in
let make_request cursor =
Client.do_get_request
~uri:(Uri.of_string base_uri) ~access_token
~uri_parameters:[
"screen_name", screen_name;
"cursor", string_of_int cursor;
"count", string_of_int count
] () in
let parse_response = function
| Error e -> Error (process_error_exn e)
| Ok (header, str) ->
match Yojson.Safe.from_string str |> user_ids_of_yojson with
| `Ok uids -> Ok uids
| `Error msg -> failwith msg in
let stream,push = Lwt_stream.create () in
let rec loop cursor =
make_request cursor >|= parse_response >>= function
| Ok {next_cursor=0} -> push None; return_unit
| Ok {next_cursor=n} as r -> push (Some r); loop n
| error -> push (Some error); loop cursor in
async (fun () -> loop (-1));
stream
Update
But of course this implementation will eagerly pull data from the server, and push it downstream. It is like a pump and pipe system. As soon as function is invoked, the pump it turned on and it will constantly pour water into the system. You can put a tap, by using bounded push, that can be obtained with Lwt_stream.create_bounded. But you will still have some amount of prefetching (or back to our pipe system analogy, you will have some kind of extension tank). Usually, this is not bad, as it removes some latency, but sometimes this is not what you want. In this case the only choice, that is left is to use explicit reference cell, to control your loop (and build stream using Lwt_stream.from). Other approach would be to change the interface, maybe you're trying to pack to much stuff into one abstraction. Maybe returning follower list Lwt.t or even follower Lwt.t list would be better. Or you can even create an abstract type follower that would hide a thread and return follower list, and lift it's accessors into the _ Lwt.t, e.g.,
module Follower : sig
type t
val name : t -> string Lwt.t
...
end
In that case, this interface can be quite usable with Lwt_list module.
Since f takes unit and produces different results each time, as you've said, it will have to depend on some state, as I think you realize. It already does that by depending on the results of I/O, and I think this is what is making the question of the ref non-trivial to answer. Otherwise, the answer would be yes, it is necessary (see point (2) below).
I think there are two main possibilities for eliminating the syntactic ref, but neither of them makes sense.
Hide these state bits somehow inside the I/O f is already doing, i.e. on the peer across the API. This doesn't seem possible, in fact it looks like the bits have to be on the client for the API to work at all.
Hide these state bits somewhere else on the client. But there will still be something spiritually equivalent to a ref somewhere in the client, in one way or another. You could write or use some kind of wrapper that factors out this ref, but unless that wrapper is useful in many places, it would only risk making it less obvious that there is extra client-side state here. I would prefer to keep the state as local and as close to its usage as possible. Since f already necessarily does "dirty" things, f is the right place.
So, in summary, I would say keep the ref as it is. It is common for streams to be stateful anyway.
The above discussion assumes that you have to use Lwt_stream. If not, you can provide an alternative interface whose type looks something like get_follower : cursor:int -> ... -> (results * cursor) Lwt.t and let the caller worry about state if it has to. This would probably be what I'd try first.
EDIT
There is of course a disadvantage to that, which is the possibility of writing the calling code to supply the wrong cursor. You could hide the cursor by returning a partially applied function, but the calling code might be written to call the wrong function. Without linear types, the stream approach is safer if you are worried about these possibilities, so it has its advantages.
I'm trying to set up dynamic loading of OCaml modules using Dynlink. I wrote a very simple test program, but it's not working.
This test program consists of two modules, Plug and Ext. Plug is the "main" module. It knows the filename of Ext and loads it with Dynlink.loadfile. Ext references Plug, and calls a function in Plug that informs Plug about one of its functions so that it can be called. After Plug loads Ext, it calls the function that Ext is supposed to have registered.
The Ext module loads successfully if I write it so that it doesn't execute any code. However, if I include the part that registers its extension function with Plug, then I get an error: The module 'Plug' is not yet initialized.
I don't understand how Plug could not be initialized yet, since it is already executing. (Actually I don't know what it means for an OCaml module to be initialized.)
I've reduced the code down to pretty much the least necessary to reproduce the problem. I am using OCaml 4.01.0 on Linux.
Here's the main module:
(* plug.ml *)
type xfn = string -> unit
let dummy_func str =
print_endline ("Dummy: " ^ str)
let ext_func : xfn ref = ref dummy_func
let register func =
ext_func := func
let call () =
(!ext_func) "calling"
(* load extension *)
let () =
try
print_endline "Loading ext.";
Dynlink.loadfile "ext.cmo";
print_endline "Loaded ext.";
()
with
| Dynlink.Error e ->
print_endline (Dynlink.error_message e);
print_endline "Calling registered func.";
call ()
This is the extension file:
(* ext.ml *)
open Plug
let myext str =
print_endline ("Ext: " ^ str)
let () = Plug.register myext
I used this shell script to compile the executable:
#!/bin/sh
ocamlc -c plug.ml && \
ocamlc -c ext.ml && \
ocamlc -o plug dynlink.cma plug.cmo ext.cmo \
|| exit 1
This is the output I get:
Loading ext.
error while linking ext.cmo.
The module `Plug' is not yet initialized
Calling registered func.
Dummy: calling
It looks like I was not on the ball with my search engine skills in this case.
Some more digging turned up an archived email chain that states that the referenced module (Plug in this case) must have been completely evaluated before the dynamically loaded module can call into it.
The solution is to separate the code that loads the extension module and the code that the extension module calls into two separate modules (so now there will be three modules in total).
I have a number of events that happen in a game. I want to control the time and order at which these events occur.
For example:
Event 1: Show some text on screen for N frames & play a sound effect
Event 2: Clear the text on the screen
My solution (maybe there is a better one), is to have a list of functions that contain the events. The events perform their behavior then return the next events to occur in the game. I thought of using List.map or List.collect because I am essentially mapping a list of events to a new list of events while performing some behavior code.
In the example above, Event1 can be composed of two functions: One that shows text and one that plays a sound (hence the need for a list). The function that shows text would return a copy of itself for N-1 frames then it would return Event2 which clears the text. The play sound function would return the equivalent of a no-op.
If this is a good solution, I could probably do it in C++ or C#. My goal is to do an equivalent or better solution in F#.
Did you mean something like this?
let myActions =
[fun () -> printfn "You've woken up a dragon."
fun () -> printfn "You hit the dragon for 0 points of damage."
fun () -> printfn "The dragon belches."
fun () -> printfn "You have died."]
let actionBuilder actionList =
let actions = ref actionList
fun () ->
match !actions with
| [] -> ()
| h::t -> h(); actions := t
Usage (F# interactive):
> let doSomething = actionBuilder myActions;;
val doSomething : (unit -> unit)
> doSomething();;
You've woken up a dragon.
val it : unit = ()
> doSomething();;
You hit the dragon for 0 points of damage.
val it : unit = ()
> doSomething();;
The dragon belches.
val it : unit = ()
> doSomething();;
You have died.
val it : unit = ()
> doSomething();;
val it : unit = ()
>
**Edit: ** if you want to be able to add actions, maybe it's better to make an action dispenser that uses a Queue internally, since appending is O(N) with a list and O(1) with a Queue:
type actionGenerator(myActions: (unit->unit) list) =
let Q = new System.Collections.Generic.Queue<_>(Seq.ofList myActions)
member g.NextAction =
fun () ->
if Q.Count = 0 then ()
else Q.Dequeue()()
member g.AddAction(action) = Q.Enqueue(action)
Not quite sure what you're trying to achieve here... it can be helpful to think through the exact types that you're looking for. It sounds like perhaps you want to map a (unit->(unit->unit)) list to a (unit->unit) list by applying each function in the first. If that's the case, you can do it like so:
let l = [(fun () -> (fun () -> printfn "first nested fn")); (fun () -> (fun () -> printfn "second nested fn"))]
let l' = List.map (fun f -> f()) l
If you are looking for a syntax to declare your list type then here is one way to do this:
List<`a->`b>
This assumes that the function takes a single parameter.
But the very fact that you are trying to figure out the syntax for the type is a hint that you are still looking at this as if you are coding in procedural language.
The "functional" way of doing it is to concentrate on the logic of generating the list and let the compiler to infer the type based on your code
I've read your question twice, and am still not sure I understand exactly what you want. But from what I understand, your 'events' aren't necessarily invoked in the order they appear in the 'list'. If this is the case, you don't really want an F# list, you want some kind of lookup.
Now the other question is whether it is really a good idea for an event to determine what should follow it? That kind of amounts to hard coding your functionality once and for all, doesn't it?
EDIT
I see in a comment that you say you want to 'chain function calls together'.
How about writing them one after the other? We aren't in Haskell after all, F# will fire them in the order you write them.
If you want to be a little bit more functional, you could use continuations - each function takes an extra parameter which is the next function to execute. Almost monadic (I believe), except that in your case they appear to be actions, so there are no values to string through from one function to the next.
Not sure if that helps: I think you'll have to try rephrasing your question, judging by the diversity of answers here.
It seems like you are trying to do something in a very complicated way. That is sometimes necessary, but usually it isn't.
Since you are asking this question, I assume that you have more experience in imperative languages. It seems that the real solution to your problem is something completely different than a list of functions.