Sml program -> confusion on "AS syntax error" - syntax

so I have to write a small program in SML ->>
a file named ‘p0.sml’ that contains a function named epoly, which accepts as parameters a list of real values a0 through an, and a single real value x. The list contains the coefficients of a polynomial of the form a0 + a1x + a2x 2 + … + anx n, where the real x used is the x parameter passed to your function. Your implementation must accept the list of coefficients as the first parameter and the value of x as the second. Your function must return the value of the polynomial specified by the parameters passed to it.
this is what I have so far but it won't compile because of a syntax error with as. "Error: syntax error found at AS". If you have any pointers that would be greatly appreciated.
fun epoly([], x:real) = 0.0
= epoly(L:real list as h::T, x:real) = h + (x * epoly(T, x));

It looks like you have a typo. Your second = should be a |.
fun epoly([], x:real) = 0.0
| epoly(L:real list as h::T, x:real) =
h + (x * epoly(T, x));
There is, further, no need to specify types. Your SML compiler can infer the types from data presented. Along with removing unnecessary bindings, this can be reduced to:
fun epoly([], _) = 0.0
| epoly(h::T, x) =
h + (x * epoly(T, x));
From fun epoly([], _) = 0.0 we know epoly will take a tuple of a list and some type and return real.
From:
| epoly(h::T, x) =
h + (x * epoly(T, x));
We know that x is being multiplied by a real, so x must be real. And since h is being added to a real, it must be a real, so the entire list is a real list.
Thus the type of epoly can be inferred correctly to be real list * real -> real.

Related

How can I emulate the results of this if then then statement while using correct syntax?

Working on an exercise for university class and cant seem to represent what I am trying to do with correct syntax in ocaml. I want the function sum_positive to sum all the positive integers in the list into a single int value and return that value.
let int x = 0 in
let rec sum_positive (ls: int list) = function
|h::[] -> x (*sum of positive ints in list*)
|[] -> 0
|h::t -> if (h >= 0) then x + h then sum_positive t else sum_positive t (*trying to ensure that sum_positive t will still run after the addition of x + h*)
On compiling I am met with this error,
File "functions.ml", line 26, characters 34-38:
Error: Syntax error
This points to the then then statement I have in there, I know it cannot work but I cant think of any other representations that would.
You have if ... then ... then which is not syntactically valid.
It seems what you're asking is how to write what you have in mind in a way that is syntactically valid. But it's not clear what you have in mind.
You can evaluate two expressions in OCaml sequentially (one after the other) by separating them with ;. Possibly that is what you have in mind.
However it seems to me your code has bigger problems than just syntax. It appears you're trying to use x as an accumulated sum for the calculation. You should be aware that OCaml variables like x are immutable. Once you say let x = 0, the value can't be changed later. x will always be 0. The expression x + h doesn't change the value of x. It just evaluates to a new value.
The usual way to make this work is to pass x as a function parameter.
I was getting an issue that had involved the parameter of , I believe it was because I was trying to add an int value to function of type int list. This is what I ended up with.
let rec sum_positive = function
|[] -> 0
|h::t -> if h > 0 then h + (sum_positive t) else sum_positive t
a lot simpler than I thought it out to be.

Implementation of (^)

I was reading the code of the implementation of (^) of the standard haskell library :
(^) :: (Num a, Integral b) => a -> b -> a
x0 ^ y0 | y0 < 0 = errorWithoutStackTrace "Negative exponent"
| y0 == 0 = 1
| otherwise = f x0 y0
where -- f : x0 ^ y0 = x ^ y
f x y | even y = f (x * x) (y `quot` 2)
| y == 1 = x
| otherwise = g (x * x) ((y - 1) `quot` 2) x
-- g : x0 ^ y0 = (x ^ y) * z
g x y z | even y = g (x * x) (y `quot` 2) z
| y == 1 = x * z
| otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
Now this part where g is defined seems odd to me why not just implement it like this:
expo :: (Num a ,Integral b) => a -> b ->a
expo x0 y0
| y0 == 0 = 1
| y0 < 0 = errorWithoutStackTrace "Negative exponent"
| otherwise = f x0 y0
where
f x y | even y = f (x*x) (y `quot` 2)
| y==1 = x
| otherwise = x * f x (y-1)
But indeed plugging in say 3^1000000 shows that (^) is about 0,04 seconds faster than expo.
Why is (^) faster than expo?
As the person who wrote the code, I can tell you why it's complex. :)
The idea is to be tail recursive to get loops, and also to perform the minimum number of multiplications. I don't like the complexity, so if you find a more elegant way please file a bug report.
A function is tail-recursive if the return value of a recursive call is returned as-is, without further processing. In expo, f is not tail-recursive, because of otherwise = x * f x (y-1): the return value of f is multiplied by x before it is returned. Both f and g in (^) are tail-recursive, because their return values are returned unmodified.
Why does this matter? Tail-recursive functions can implemented much more efficiently than general recursive functions. Because the compiler doesn't need to create a new context (stack frame, what have you) for a recursive call, it can reuse the caller's context as the context of the recursive call. This saves a lot of the overhead of calling a function, much like in-lining a function is more efficient than calling the function proper.
Whenever you see a bread-and-butter function in the standard library and it's implemented weirdly, the reason is almost always "because doing it like that triggers some special performance-critical optimization [possibly in a different version of the compiler]".
These odd workarounds are usually to "force" the compiler to notice that some specific, important optimization is possible (e.g., to force a particular argument to be considered strict, to allow worker/wrapper transformation, whatever). Typically some person has compiled their program, noticed it's epicly slow, complained to the GHC devs, and they looked at the compiled code and thought "oh, GHC isn't seeing that it can inline that 3rd worker function... how do I fix that?" The result is that if you rephrase the code just slightly, the desired optimization then fires.
You say you tested it and there's not much speed difference. You didn't say for what type. (Is the exponent Int or Integer? What about the base? It's quite possible it makes a significant difference in some obscure case.)
Occasionally functions are also implemented weirdly to maintain strictness / laziness guarantees. (E.g., the library spec says it has to work a certain way, and implementing it the most obvious way would make the function more strict / less strict than the spec claims.)
I don't know what's up with this specific function, but I would suggest #chi is probably onto something.

Extending Immutable types (or: fast cache for immutable types) in OCaml

I have a recursive immutable data structure in ocaml which can be simplified to something like this:
type expr =
{
eexpr : expr_expr;
some_other_complex_field : a_complex_type;
}
and expr_expr =
| TInt of int
| TSum of (expr * expr)
| TMul of (expr * expr)
It's an AST, and sometimes it gets pretty complex (it's very deep).
there is a recursive function that evaluates an expression. For example, let's say,
let rec result expr =
match expr.eexpr with
| TInt i -> i
| TSum (e1, e2) -> result e1 + result e2
| TMul (e1, e2) -> result e1 * result e2
Now suppose I am mapping an expression to another expression, and I need to constantly check the result of an expr, sometimes more than once for the same expr, and sometimes for expressions that were recently mapped by using the pattern
{ someExpr with eexpr = TSum(someExpr, otherExpr) }
Now, the result function is very lightweight, but running it many times for a deep AST will not be very optimized. I know I could cache the value using a Hashtbl, but AFAIK the Hashtbl will only do structural equality, so it will need to traverse my long AST anyway.
I know the best option would be to include a probably immutable "result" field in the expr type. But I can't.
So is there any way in Ocaml to cache a value to an immutable type, so I don't have to calculate it eagerly every time I need it ?
Thanks!
Hash-cons the values of expr_expr. By doing this structurally equal values in your program will share exactly the same memory representation and you can substitute structural equality (=) by physical equality (==).
This paper should get you quickly started on hash-consing in OCaml.
You can use the functorial interface to control the kind of equality used by the hash table. I believe the semantics of (==) are legitimate for your purposes; i.e., if A == B then f A = f B for any pure function f. So you can cache the results of f A. Then if you find a B that's physically equal to A, the cached value is correct for B.
The downside of using (==) for hashing is that the hash function will send all structurally equal objects to the same hash bucket, where they will be treated as distinct objects. If you have a lot of structurally equal objects in the table, you get no benefit from the hashing. The behavior degenerates to a linear search.
You can't define the hash function to work with physical addresses, because the physical addresses can be changed at any time by the garbage collector.
However, if you know your table will only contain relatively few large-ish values, using physical equality might work for you.
I think you can merge the two ideas above : use hash-consing-like techniques to get the hash of the "pure expression" part of your data, and use this hash as key in the memoization table for the eval function.
Of course this only works when your eval function indeed only depends on the "pure expression" part of the function, as in the example you gave. I believe that is a relatively general case, at least if you restrict yourself to storing the successful evaluations (that won't, for example, return an error including some location information).
Edit: a small proof of concept:
type 'a _expr =
| Int of int
| Add of 'a * 'a
(* a constructor to avoid needing -rectypes *)
type pure_expr = Pure of pure_expr _expr
type loc = int
type loc_expr = {
loc : loc;
expr : loc_expr _expr;
pure : pure_expr (* or any hash_consing of it for efficiency *)
}
(* this is where you could hash-cons *)
let pure x = Pure x
let int loc n =
{ loc; expr = Int n; pure = pure (Int n) }
let add loc a b =
{ loc; expr = Add (a, b); pure = pure (Add(a.pure, b.pure)) }
let eval =
let cache = Hashtbl.create 251 in
let rec eval term =
(* for debug and checking memoization *)
Printf.printf "log: %d\n" term.loc;
try Hashtbl.find cache term.pure with Not_found ->
let result =
match term.expr with
| Int n -> n
| Add(a, b) -> eval a + eval b in
Hashtbl.add cache term.pure result;
result
in eval
let test = add 3 (int 1 1) (int 2 2)
# eval test;;
log: 3
log: 2
log: 1
- : int = 3
# eval test;;
log: 3
- : int = 3

What's the formal term for a function that can be written in terms of `fold`?

I use the LINQ Aggregate operator quite often. Essentially, it lets you "accumulate" a function over a sequence by repeatedly applying the function on the last computed value of the function and the next element of the sequence.
For example:
int[] numbers = ...
int result = numbers.Aggregate(0, (result, next) => result + next * next);
will compute the sum of the squares of the elements of an array.
After some googling, I discovered that the general term for this in functional programming is "fold". This got me curious about functions that could be written as folds. In other words, the f in f = fold op.
I think that a function that can be computed with this operator only needs to satisfy (please correct me if I am wrong):
f(x1, x2, ..., xn) = f(f(x1, x2, ..., xn-1), xn)
This property seems common enough to deserve a special name. Is there one?
An Iterated binary operation may be what you are looking for.
You would also need to add some stopping conditions like
f(x) = something
f(x1,x2) = something2
They define a binary operation f and another function F in the link I provided to handle what happens when you get down to f(x1,x2).
To clarify the question: 'sum of squares' is a special function because it has the property that it can be expressed in terms of the fold functional plus a lambda, ie
sumSq = fold ((result, next) => result + next * next) 0
Which functions f have this property, where dom f = { A tuples }, ran f :: B?
Clearly, due to the mechanics of fold, the statement that f is foldable is the assertion that there exists an h :: A * B -> B such that for any n > 0, x1, ..., xn in A, f ((x1,...xn)) = h (xn, f ((x1,...,xn-1))).
The assertion that the h exists says almost the same thing as your condition that
f((x1, x2, ..., xn)) = f((f((x1, x2, ..., xn-1)), xn)) (*)
so you were very nearly correct; the difference is that you are requiring A=B which is a bit more restrictive than being a general fold-expressible function. More problematically though, fold in general also takes a starting value a, which is set to a = f nil. The main reason your formulation (*) is wrong is that it assumes that h is whatever f does on pair lists, but that is only true when h(x, a) = a. That is, in your example of sum of squares, the starting value you gave to Accumulate was 0, which is a does-nothing when you add it, but there are fold-expressible functions where the starting value does something, in which case we have a fold-expressible function which does not satisfy (*).
For example, take this fold-expressible function lengthPlusOne:
lengthPlusOne = fold ((result, next) => result + 1) 1
f (1) = 2, but f(f(), 1) = f(1, 1) = 3.
Finally, let's give an example of a functions on lists not expressible in terms of fold. Suppose we had a black box function and tested it on these inputs:
f (1) = 1
f (1, 1) = 1 (1)
f (2, 1) = 1
f (1, 2, 1) = 2 (2)
Such a function on tuples (=finite lists) obviously exists (we can just define it to have those outputs above and be zero on any other lists). Yet, it is not foldable because (1) implies h(1,1)=1, while (2) implies h(1,1)=2.
I don't know if there is other terminology than just saying 'a function expressible as a fold'. Perhaps a (left/right) context-free list function would be a good way of describing it?
In functional programming, fold is used to aggregate results on collections like list, array, sequence... Your formulation of fold is incorrect, which leads to confusion. A correct formulation could be:
fold f e [x1, x2, x3,..., xn] = f((...f(f(f(e, x1),x2),x3)...), xn)
The requirement for f is actually very loose. Lets say the type of elements is T and type of e is U. So function f indeed takes two arguments, the first one of type U and the second one of type T, and returns a value of type U (because this value will be supplied as the first argument of function f again). In short, we have an "accumulate" function with a signature f: U * T -> U. Due to this reason, I don't think there is a formal term for these kinds of function.
In your example, e = 0, T = int, U = int and your lambda function (result, next) => result + next * next has a signaturef: int * int -> int, which satisfies the condition of "foldable" functions.
In case you want to know, another variant of fold is foldBack, which accumulates results with the reverse order from xn to x1:
foldBack f [x1, x2,..., xn] e = f(x1,f(x2,...,f(n,e)...))
There are interesting cases with commutative functions, which satisfy f(x, y) = f(x, y), when fold and foldBack return the same result. About fold itself, it is a specific instance of catamorphism in category theory. You can read more about catamorphism here.

about plotting process -- a further question about "A problem in Mathematica 8 with function declaration"

Related A problem in Mathematica 8 with function declaration
Clear["Global`*"]
model = 4/Sqrt[3] - a1/(x + b1) - a2/(x + b2)^2 - a3/(x + b3)^4;
fit = {a1 -> 0.27, a2 -> 0.335, a3 -> -0.347, b1 -> 4.29, b2 -> 0.435,
b3 -> 0.712};
functionB1[x_] = model /. fit;
functionB2[x_] := model /. fit;
The evaluation difference between functionB1 and functionB2 can be revealed by Trace command in mma, as below:
functionB1[Sqrt[0.2]] // Trace
functionB2[Sqrt[0.2]] // Trace
I have no question about functionB1. what puzzles me is that because functionB2[Sqrt[0.2]] doesn't even gives a numeric result but gives a function of x 4/Sqrt[3] - 0.335/(0.435 + x)^2 + 0.347/(0.712 + x)^4 - 0.27/(
4.29 + x), and then how its plot Plot[functionB2[Sqrt[x]], {x, 0, 1}] is possible?
I mean when you run Plot[functionB2[Sqrt[x]], {x, 0, 1}], what happens inside mma is:
x takes a number, say, 0.2, then 0.2 is finally passed to functionB2, but functionB2 gives a function, not a number. Then how is the following figure generated?
And its trace result ( Plot[functionB2[Sqrt[x]], {x, 0, 1}] // Trace ) seems very unreadable. I wonder the clear plotting process of functionB2. Can anybody show it?
thanks~ :)
SetDelayed acts as a scoping construction. Arguments are localized if necessary. Any variables that explicitly match the arguments are bound within this scope, others are not.
In[78]:= a[x_] := x^2 + b
b = x^4;
(* the first x^2 is explicitly present and bound to the argument.
The x in x^4 present via b is not bound *)
In[80]:= a[x]
Out[80]= x^2 + x^4 (* this is what you would expect *)
In[81]:= a[y]
Out[81]= x^4 + y^2 (* surprise *)
In[82]:= a[1]
Out[82]= 1 + x^4 (* surprise *)
So, what you could do is one of two things:
Use Evaluate: functionB2[x_] := Evaluate[model /. fit];
Make dependence of model on x explicit:
In[68]:= model2[x_] =
4/Sqrt[3] - a1/(x + b1) - a2/(x + b2)^2 - a3/(x + b3)^4;
In[69]:= functionB3[x_] := model2[x] /. fit;
In[85]:= functionB3[Sqrt[0.2]]
Out[85]= 2.01415
Edit because of question update
Because of your definition of functionB2 any argument value yields the same result, as explained above:
In[93]:= functionB2[1]
Out[93]= 4/Sqrt[3] - 0.335/(0.435 + x)^2 + 0.347/(0.712 +
x)^4 - 0.27/(4.29 + x)
In[94]:= functionB2["Even a string yields the same ouput"]
Out[94]= 4/Sqrt[3] - 0.335/(0.435 + x)^2 + 0.347/(0.712 +
x)^4 - 0.27/(4.29 + x)
However, this expression contains x's and therefore it can get a numerical value if we provide a numerical value for x:
In[95]:= functionB2["Even a string yields the same ouput"] /. x -> 1
Out[95]= 2.13607
Well, this basically what Plot does too. This is why you still get a plot.
The definition:
functionB2[x_] := model /. fit
is an instruction to Mathematica to replace all future occurrences of an expression that looks like functionB2[x_] with the result of substituting the value of the argument for every occurrence of x in the expression model /. fit. But there are no occurrences of x in model /. fit: the only symbols in that expression are model and fit (and, technically, ReplaceAll). Therefore, the definition returns a fixed result, model /. fit, irrespective of the argument. Indeed, the definition could just simply be:
functionB2a[] := model /. fit
If you plot functionB2a[], you will get the same result as if you plotted functionB2[anything]. Why? Because Plot will evaluate that expression while varying the symbol x over the plot range. It so happens that model /. fit evaluates to an expression involving that symbol, so you get the exhibited plot.
Now consider functionB1:
functionB1[x_] = model /. fit
It too says to replace all occurrences of x on the right-hand side -- but this time the right-hand side is evaluated before the definition is established. The result of evaluating model /. fit is an expression that does contain the symbol x, so now the definition is sensitive to the passed argument value. The net result is as if the function were defined thus:
functionB1a[x_] := 4/Sqrt[3]-0.335/(0.435+x)^2+0.347/(0.712+x)^4-0.27/(4.29+x)
So, if you plot functionB1[Sqrt[x]], the Plot command will see the expression:
4/Sqrt[3]-0.335/(0.435 +Sqrt[x])^2+0.347/(0.712 +Sqrt[x])^4-0.27/(4.29 +Sqrt[x])
Formal Symbols
When establishing definitions using SetDelayed, the name of the formal argument (x in this case) is independent of any occurrences of the same symbol outside of the definition. Such definitions can use any other symbol, and still generate the same result. On the other hand, definitions established using Set (such as functionB1) rely on the result of evaluating the right-hand side containing the same symbol as the formal argument. This can be a source of subtle bugs as one must take care not use symbols that accidentally have pre-existing down-values. The use of formal symbols (described in Letters and Letter-like Forms) for argument names can help manage this problem.
You can understand what is going on by trying:
Table[functionB2[Sqrt[y]],{y,0.5,.5,.5}]
Table[functionB2[Sqrt[x]],{x,0.5,.5,.5}]
(*
{4/Sqrt[3] - 0.335/(0.435+ x)^2 + 0.347/(0.712+ x)^4 - 0.27/(4.29+ x)}
{2.03065}
*)
What is getting replaced is the x inside the definition of functionB2, not a formal argument.
Edit
The plot you are getting is not what you want. The Sqrt[x] is disregarded in functionB2[...] and the implicit x is replaced, as you can see here:

Resources