Ocaml multi-line function in REPL - ocaml

I'm trying to write a multi-line function to use in an OCaml REPL. I've already seen this question, but the syntax suggested doesn't seem to work when using it in a REPL.
To use a contrived example, I can't get the following to compile:
let theFun: int -> int = fun x ->
let foo = x;
foo;;
When I enter it without the ";;" in this online REPL, they get added in anyway and it gives me a syntax error. When I use a REPL on my local machine, the input won't get evaluated unless I include the ";;", and that gives me a syntax error as well.

Your example is incorrect, a proper way to do it will be
let theFun: int -> int = fun x ->
let foo = x in
foo;;

Related

Is it possible to trace auxiliary functions in the Ocaml REPL

What I would like to do is trace the function aux that has restricted scope in a definition like:
let example = function
arg ->
let rec aux =
(* some recursive function body*)
in
aux arg
;;
with #trace or a similar toplevel command, so that the trace appears when example is called.
(without just copy-pasting the auxiliary function under some other name and passing it to the toplevel)
note: I am using tuareg mode on emacs
No. In the toplevel, you can trace only toplevel functions.

Is there a way to display every function of a SML package/library? I am using PolyML

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
...

Any good usage examples of an AST transformation with ppx_driver (register_transformation_using_ocaml_current_ast)?

tl;dr I'm trying to make a source transformation binary using AST_mapper and ppx_driver. I can't figure out how to get the example in the AST_mapper docs to be used by ppx_driver. Are there any good examples of how to use Ppx_driver.register_transformation_using_ocaml_current_ast?
I'm trying to port the example AST_mapper in the docs to be compatible with ppx_driver. Specifically, I'm looking to create a binary that takes source as input, transforms the source using this test mapper, and then outputs the transformed source. Unfortunately, the default main provided by Ast_mapper only accepts Ocaml AST as input (and presumably produces it as output). This is undesirable, because I don't want to have to run this through ocamlc with -dsource to get my output.
Here's my best stab at porting this:
test_mapper.ml
open Asttypes
open Parsetree
open Ast_mapper
let test_mapper argv =
{ default_mapper with
expr = fun mapper expr ->
Pprintast.expression Format.std_formatter expr;
match expr with
| { pexp_desc = Pexp_extension ({ txt = "test" }, PStr [])} ->
Ast_helper.Exp.constant (Ast_helper.Const.int 42)
| other -> default_mapper.expr mapper other; }
let test_transformation ast =
let mapper = (test_mapper ast) in
mapper.structure mapper ast
let () =
Ppx_driver.register_transformation_using_ocaml_current_ast
~impl:test_transformation
"test_transformation"
A few things to note:
The example from the docs didn't work out of the box (before introducing ppx_driver): Const_int 42 had to be replaced with Ast_helper.Const.int 42
For some reason test_mapper is Parsetree.structure -> mapper. (It is unclear to me why a recursive transformation needs the structure to create the mapper, but no matter.) But, this type isn't what Ppx_driver.register_transformation_using_ocaml_current_ast expects. So I wrote a sloppy wrapper test_transformation to make the typechecker happy (that is loosely based off how Ast_mapper.apply_lazy appears to apply a mapper to an AST so in theory it should work)
Unfortunately, after compiling this into a binary:
ocamlfind ocamlc -predicates ppx_driver -o test_mapper test_mapper.ml -linkpkg -package ppx_driver.runner
And running it on a sample file:
sample.ml
let x _ = [%test]
with the following:
./test_mapper sample.ml
I don't see any transformation occur (the sample file is regurgitated verbatim). What's more, the logging Pprintast.expression that I left in the code doesn't print anything, which suggests to me that my mapper never visits anything.
All of the examples I've been able to find in the wild are open sourced by Jane Street (who wrote ppx_*) and seem to either not register their transformation (perhaps there's some magic detection going on that's going over my head) or if they do they use Ppx_driver.register_transformation ~rules which uses Ppx_core.ContextFree (which doesn't seem to be complete and won't work for my real use case--but for the purposes of this question, I'm trying to keep things generally applicable).
Are there any good examples of how to do this properly? Why doesn't ppx_driver use my transformation?
If you want to make a standalone rewriter with a single module, you need to add
let () = Ppx_driver.standalone ()
to run the rewriter and links with ppx_driver and not ppx_driver.runner: ppx_driver.runner runs the driver as soon as it is loaded, therefore before your transformation is registered. Note also that you should at least specify a specific Ast version and uses Ppx_driver.register_transformation rather than Ppx_driver.register_transformation_using_current_ocaml_ast otherwise there is little point in using ppx_driver rather than doing the parsing by hand with compiler-libs and the Pparse module.

Avoiding object

I'm trying to write a simple tower defense game in OCaml as a bit of a learning project and I'm having a problem with how I structure my code. I've been trying to avoid using classes/objects to represent my towers and enemies mostly because I haven't learnt how ocaml objects work, but mostly because I seem to have picked up an aversion to using them from my reading about OCaml. Anyway, what I've been trying to do is have a module for each type of tower, which all have the same signature (TOWER), implementing functions that the mainloop uses to update the game. My idea was to use first class modules so I could then have a function like
let create m =
let module M = (val m : TOWER) in
M.create ()
where TOWER is
module type TOWER = sig
type t
...
val create : unit -> t
end
But now I have a problem in that it seems that when you unwrap a first class module you get a brand new module, whereas I assumed you'd get something like an alias for the module, so at compile time I get an error saying there's a problem with the scope of the type constructor for M.t. From this and the tinkering I've tried to do it seems that my original idea of using first class modules to decide which function to use won't work unless I move the type declaration out of TOWER and make it a shared type that all towers use. Is there a way to get the effect I'm looking for or would I have to some other technique?
If you're using a first class module in a function, and there exists a type constructor in a function type, that depends on a type that is defined inside the module, then it means, that the type escape its scope, and you need to put your function into a prenex normal form, by bounding this type to a new type variable. To clarify this here is the example:
let create_tower (module T : TOWER) = T.create ()
This will not compile, since T.t. escapes the scope. Try to write a type for the function create_tower: (module TOWER) -> ?. We don't have a name for the type t, that is in the scope of the TOWER signature. So we need to bring it out, to get the following type:
(module TOWER with type t = 'a) -> 'a
To get this, we use the following syntax:
let create_tower (type t) (module T : TOWER with type t = t) =
T.create ()
Now it works.
And a usual rant about modules. There is no need to use modules or objects here. Just use records to represent your towers and enemies.
If you use a sum type to represent different towers, you don't have to bother with modules or objects.
For example :
type tower =
| SimpleTower
| SuperTower of int
type position = int * int
type pos_tower = position * tower
let string_of_tower = function
| SimpleTower -> "Simple tower"
| SuperTower i -> "Super Tower level " ^ (string_of_int i)
;;
let my_towers = [ ((0,0) , SimpleTower) ; ( (10,0) , SuperTower 5) ] ;;
The properties of such an architecture are dual to the properties of an object oriented architecture (functions are modular here whereas they crosscut in an object architecture).

F#: Storing and mapping a list of functions

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.