Why does camlp4o fail to parse (or) as a binary function? - ocaml

In vanilla OCaml, (or) is a binary function just like (+) and all the others, so code like this works fine:
let any (truths:bool list) = List.fold_left (or) false truths
But in any environment where camlp4o is loaded, this fails to parse with:
Error: Parse error: ")" or "module" or [expr] expected after "(" (in [expr])
Meanwhile, (+) and the other integer arithmetic operators continue to work as expected in either environment:
let sum (nums:int list) = List.fold_left (+) 0 nums
Why is this? Is this a limitation with camlp4o, or a bug? This occurs on OCaml 3.12.1 (on OS X 10.7.4, installed freshly via GODI bootstrap).

This is a known bug that has been fixed since. The soon to be released 4.00 version will not have that issue.
PS: when I find something suspicious about OCaml that I strongly suspect is a bug, my technique is to do a google search with the site:caml.inria.fr/mantis modifier to search the OCaml bugtracker for similar content.

In "normal" OCaml you can use (or) interchangeably with (||). If you look at the definition of the revised syntax, the use of (or) is not supported. You always need to use (||). Perhaps this is a side effect of that change?
At any rate, some quick tests indicate that (||) works with camlp4o.

Related

Why my OCaml "=" operator is only applied to int?

I use vscode, with extensions of "OCaml and Reason IDE"
Here is my result in utop:
utop # 1. = 1. ;;
Line 1, characters 0-2:
Error: This expression has type float but an expression was expected of type
int
And also for String:
utop # "Me" = "Me";;
Line 1, characters 0-4:
Error: This expression has type string but an expression was expected of type
int
Same for anything but int:
utop # 2 = 2 ;;
- : bool = true
">" "<" also have the same symptom. I don't know what actually happens. Can anyone help me out ? Thanks a lot!
You are probably using JaneStreet Base library. Maybe you imported it like that:
open Base;;
Base tries to limit exceptions to functions that have explicit _exn suffix, so it shadows the built-in polymorphic equality (=) which can raise an exception on some inputs (for example, if you compare structures containing functions).
You can get polymorphic equality back as follows:
let (=) = Poly.(=);;
Or you can use it with a local import: Poly.(x = y).
There are pros and cons to polymorphic comparison.
The consensus seems to be that using monomorphic comparison (for example, String.equal, etc) is a more robust choice, even though it is less convenient.

Parenthesis calculator for C/C++ expressions operator precedence

After porting some obfuscated C code into C++ (namely Fairy-Max chess engine by Harm Geert Muller), I get lots of warnings similar to these:
suggest parentheses around comparison in operand of '&' [-Werror=parentheses]
suggest parentheses around '+' in operand of '&'
While turning off the warnings is not an option, the solution is to add parenthesis in expressions according to the operator precedence.
For example:
if(z&S&&!ab&K==INF&d>2&v>V&v<Beta){
needs to be transformed into this:
if((z&S) && ((!ab)&(K==INF)&(d>2)&(v>V)&(v<Beta))) {
But doing this manually is quite time-consuming.
I tried to use this deobfuscation tool, which uses clang-format internally, but it does not add parenthesis into expressions...
Question
Is there a tool (preferably online) that can take a C/C++ expression as an input and return a warnings-free equivalent expression as an output?
Geordi can do it.
I've long wanted a web version, but last time I tried to get Geordi working on my VPS I failed miserably due to Haskell dependency gubbins. May give it another go one day.
Meanwhile, you can log onto Freenode IRC and /msg geordi --precedence *p->data (for example). You'll get a private message tab open up with the result (e.g. *(p->data)). Feel free to keep sending --precedence <expression> requests in that tab.

"Eval" a string in OCaml

I'm trying to "eval" a string representing an OCaml expression in OCaml. I'm looking to do something equivalent to Python's eval.
So far I've not been able to find much. The Parsing module looks like it could be helpful, but I was not able to find a way to just eval a string.
Here is how to do it, but I didn't tell you. (Also the Parsing module is about Parsing, not executing code)
#require "compiler-libs" (* Assuming you're using utop, if compiling then this is the package you need *)
let eval code =
let as_buf = Lexing.from_string code in
let parsed = !Toploop.parse_toplevel_phrase as_buf in
ignore (Toploop.execute_phrase true Format.std_formatter parsed)
example:
eval "let () = print_endline \"hello\";;"
Notice the trailing ;; in the code sample.
To use ocamlbuild, you will need to use both compiler-libs and compiler-libs.toplevel.
OCaml is a compiled (not interpreted) language. So there's no simple way to do this. Certainly there are no language features that support it (as there are in almost every interpreted language). About the best you could do would be to link your program against the OCaml toplevel (which is an OCaml interpreter).

Haskell: should I bother compiling regular expressions?

My impulse is to say yes, especially if I'm using the same regex in multiple code locations, but this article indicates that the library will cache the compilation for me (which I'm not even sure how it would do):
There’s normally no need to compile regular expression patterns. A pattern will be compiled the first time it’s used, and your Haskell runtime should memoise the compiled representation for you.
If you reuse a regular expression then it is worthwhile to use the RegexMaker type class to define the "compiled" regular expression. It has the ability to take additional options and the ability to report compilation failure in your choice of Monad.
To use the "compiled" form you can use 'match' or 'matchM' from RegexLike which gives you the equivalent to =~ or ==~ operators.
GHC (as of 7.8.4/regex-tdfa-1.2.0) does not memoize regular expressions matched with (=~) or (=~~). I see an order of magnitude performance improvement using compile and execute with a large number of potential matches.
compile and execute
(=~)

Dynamically Describing Mathematical Rules

I want to be able to specify mathematical rules in an external location to my application and have my application process them at run time and perform actions (again described externally). What is the best way to do this?
For example, I might want to execute function MyFunction1() when the following evaluates to true:
(a < b) & MyFunction2() & (myWord == "test").
Thanks in advance for your help.
(If it is of any relevance, I wish to use C++, C or C++/CLI)
I'd consider not reinventing the wheel --- use an embedded scripting engine. This means you'd be using a standard form for describing the actions and logic. There are several great options out there that will probably be fine for your needs.
Good options include:
Javascript though google v8. (I don't love this from an embedding point of view,
but javascript is easy to work with, and many people already know it)
Lua. Its fast and portable. Syntax is maybe not as nice as Javascript, but embedding is
easy.
Python. Clean syntax, lots of libraries. Not much fun to embed though.
I'd consider using SWIG to help generate the bindings ... I know it works for python and lua, not sure about v8.
I would look at the command design pattern to handle calling external mathematical predicates, and the Factory design pattern to run externally defined code.
If your mathematical expression language is that simple then uou could define a grammar for it, e.g.:
expr = bin-op-expr | rel-expr | func-expr | var-expr | "(" expr ")"
bin-op = "&" | "|" | "!"
bin-op-expr = expr bin-op expr
rel-op = "<" | ">" | "==" | "!=" | "<=" | ">="
rel-expr = expr rel-op expr
func-args = "(" ")"
func-expr = func-name func-args
var-expr = name
and then translate that into a grammar for a parser. E.g. you could use Boost.Spirit which provides a DSL to allow you to express a grammar within your C++ code.
If that calculation happens at an inner loop, you want high performance, you cannot go with scripting languages. Based on how "deployable" and how much platform independent you would like that to be:
1) You could express the equations in C++ and let g++ compile it for you at run-time, and you could link to the resulting shared object. But this method is very much platform dependent at every step! The necessary system calls, the compiler to use, the flags, loading a shared object (or a DLL)... That would be super-fast in the end though, especially if you compile the innermost loop with the equation. The equation would be inlined and all.
2) You could use java in the same way. You can get a nice java compiler in java (from Eclipse I think, but you can embed it easily). With this solution, the result would be slightly slower (depending on how much template magic you want), I would expect, by a factor of 2 for most purposes. But this solution is extremely portable. Once you get it working, there's no reason it shouldn't work anywhere, you don't need anything external to your program. Another down side to this is having to write your equations in Java syntax, which is ugly for complex math. The first solution is much better in that respect, since operator overloading greatly helps math equations.
3) I don't know much about C#, but there could be a solution similar to (2). If there is, I know that there's operator overloading in C#, so your equations would be more pleasant to write and look at.