OCaml function syntax error - function

The following code gives an error:
let alpha = Hashtbl.create 26 in
let print_and_add a =
print_char a;
Hashtbl.add alpha a true;;
let str = read_line () in
String.iter (fun x -> if Hashtbl.mem alpha x=false then print_and_add x) str
What it's supposed to do:each time the function is called (with a char argument),it should print the char,and add it to the Hash table (alpha).
I tried using the other syntax for functions:
let alpha = Hashtbl.create 26 in
let print_and_add = (fun a ->
print_char a;
Hashtbl.add alpha a true) in
let str = read_line () in
String.iter (fun x -> if Hashtbl.mem alpha x=false then print_and_add x) str
But I still want to know why the first code fails.
-Thanks for any help.

The ;; symbol specifically marks the end of an expression at the global level. So everything after it has to be part of a different expression. Hence alpha can't be defined after that.
I never use ;; in source code, only when typing to the toplevel. In my opinion, that's what it's for.
Your code also has let print_and_add ... without a corresponding in. This is valid only at the global level (not inside an expression).
If you change ;; to in in your original code, you get something that works. At least it works for me.

alpha is no longer in scope when you attempt to use it the second time in the first snippet.

Related

OCaml meaning of "in"

Lets assume the following function
val foo : int -> int -> bool -> int
let foo x y b =
let x,y = if x > y then y,x else x,y in
let rec loop x y b =
if x >= then x
else if b then loop (x+1) y (not b)
else loop x (y-1) (not b)
in
loop x y b
I still don't quite understand the concept of the "in".
Does the line mean "let x,y = ... in" that it is executed immediately or only when you "Call" it? And when i dont need to call it why do i need the last line loop x y b?
Thanks in advance :)
in is just part of the OCaml syntax - let PATTERN = EXPR1 in EXPR2 is an expression which binds the result of EXPR1 to PATTERN and then evaluates EXPR2 with the new bindings present. In some languages like F# and Haskell, you don't (always) need in - it's inferred from the indentation. OCaml syntax is indentation insensitive which requires it to have an explicit in.
Does the line mean "let x,y = ... in" that it is executed immediately or only when you "Call" it?
It's evaluated immediately.
And when i dont need to call it why do i need the last line loop x y b?
In this code, the previous line defines a function named loop with 3 arguments, and then later you call the function with the arguments x y b.

Using the fun keyword in ocaml

Since Ocaml utilizes type inferences, and functions are a type, do I have to use fun to declare a function? For example, the REPL/interpreter for Ocaml executes this statement without complaint:
let average a b =
(a +. b) /. 2.0;;
Does this mean that I can dispense with fun when declaring functions? When is it needed, or is it ever needed?
The keyword fun is needed with anonymous functions. For instance, the following code doubles each elements of the list l = [ 1; 2; 3; 4]
let l = [1; 2; 3; 4]
let doubled_l = List.map (fun x -> 2 * x) l
but this snippet could be rewritten as
let l = [1; 2; 3; 4]
let double x = 2 * x
let doubled_l = List.map double l
( or even List.map ( ( * ) 2 ) l )
Contrarily, your average function could be rewritten as
let average = fun x y -> (x +. y) /. 2.
or
let average = fun x -> fun y -> (x +. y) /. 2.
(the syntax average x y = ... is in fact a syntactic sugar for this form)
let average a b = ... is exactly equivalent to let average = fun a b -> ... - you can always use the former over the latter. It's just a matter of style which one you prefer. My feeling is that most programmers use the former form, but some introductory materials use the latter form to make it clear that functions are values just like any other and can be created using the fun keyword.
However let f = fun ... is not the only way to use fun. You can use it wherever a value of a function type is expected, for example as an argument to map. So if you have something like List.map (fun x -> x+1) xs, you can't just put a let in place of the fun because a definition makes no syntactic sense there. You could of course use let add1 x = x+1 in List.map add1 xs and that works fine, but that's more verbose and introduces a new name that's only used once and doesn't really add anything.
So fun is useful when you want to pass a function around without giving it a name.

Piecewise functions in the Octave symbolic package?

Unlike Matlab, Octave Symbolic has no piecewise function. Is there a work around? I would like to do something like this:
syms x
y = piecewise(x0, 1)
Relatedly, how does one get pieces of a piecewise function? I ran the following:
>> int (exp(-a*x), x, 0, t)
And got the following correct answer displayed and stored in a variable:
t for a = 0
-a*t
1 e
- - ----- otherwise
a a
But now I would like to access the "otherwise" part of the answer so I can factor it. How do I do that?
(Yes, I can factor it in my head, but I am practicing for when more complicated expressions come along. I am also only really looking for an approach using symbolic expressions -- even though in any single case numerics may work fine, I want to understand the symbolic approach.)
Thanks!
Matlab's piecewise function seems to be fairly new (introduced in 2016b), but it basically just looks like a glorified ternary operator. Unfortunately I don't have 2016 to check if it performs any checks on the inputs or not, but in general you can recreate a 'ternary' operator in octave by indexing into a cell using logical indexing. E.g.
{#() return_A(), #() return_B(), #() return_default()}([test1, test2, true]){1}()
Explanation:
Step 1: You put all the values of interest in a cell array. Wrap them in function handles if you want to prevent them being evaluated at the time of parsing (e.g. if you wanted the output of the ternary operator to be to produce an error)
Step 2: Index this cell array using logical indexing, where at each index you perform a logical test
Step 3: If you need a 'default' case, use a 'true' test for the last element.
Step 4: From the cell (sub)array that results from above, select the first element and 'run' the resulting function handle. Selecting the first element has the effect that if more than one tests succeed, you only pick the first result; given the 'default' test will always succeed, this also makes sure that this is not picked unless it's the first and only test that succeeds (which it does so by default).
Here are the above steps implemented into a function (appropriate sanity checks omitted here for brevity), following the same syntax as matlab's piecewise:
function Out = piecewise (varargin)
Conditions = varargin(1:2:end); % Select all 'odd' inputs
Values = varargin(2:2:end); % Select all 'even' inputs
N = length (Conditions);
if length (Values) ~= N % 'default' case has been provided
Values{end+1} = Conditions{end}; % move default return-value to 'Values'
Conditions{end} = true; % replace final (ie. default) test with true
end
% Wrap return-values into function-handles
ValFuncs = cell (1, N);
for n = 1 : N; ValFuncs{n} = #() Values{n}; end
% Grab funhandle for first successful test and call it to return its value
Out = ValFuncs([Conditions{:}]){1}();
end
Example use:
>> syms x t;
>> F = #(a) piecewise(a == 0, t, (1/a)*exp(-a*t)/a);
>> F(0)
ans = (sym) t
>> F(3)
ans = (sym)
-3⋅t
ℯ
─────
9

How I can change the variable in this for loop

I've a problem with a loop for. In this program,
let f s =
for i = 0 to ((String.length s) - 1) do
print_char s.[i];
done;;
For some reasons, I want to change the variable i (increase,dicrease) but this variable is not mutable and I don't see how I can change the pointer on the string s. I think to an another function which but I don't know if is the good idea ..

F# Function doesn't let me mutate mutable value

Probably another dumb F# beginner's question... But it's bugging me all the same
I can't seem to find any answers to this online... might be 'cause I search the wrong terms but eh
anyway my code goes as follows:
let counter() =
let mutable x = 0
let increment(y :int) =
x <- x + y // this line is giving me trouble
printfn "%A" x // and this one too
increment // return the function
Visual Studio is telling me that x is used in an invalid way, that mutable variables can't be captured by closures
why is that? and what can I do to allow me to mutate it?
As the error message indicates, you can use a ref cell instead:
let counter() =
let x = ref 0
let increment(y :int) =
x := !x + y // this line is giving me trouble
printfn "%A" !x // and this one too
increment // return the function
This does exactly what your code would do if it were legal. The ! operator gets the value out of the ref cell and := assigns a new value. As to why this is required, it's because the semantics of capturing a mutable value by a closure have proven to be confusing; using a ref cell makes things somewhat more explicit and less error-prone (see http://lorgonblog.wordpress.com/2008/11/12/on-lambdas-capture-and-mutability/ for further elaboration).