I want to find the first occurence of a digit in a list :
let pos_list = function (list , x) ->
let rec pos = function
|([] , x , i) -> i
|([y] , x , i) -> if y == x then i
|(s::t , x , i) -> if s == x then i else pos(t , x , i + 1) in pos(list , x , 0) ;;
but the compiler complain that the expression is a "uint" type , and was used instead with a "int" type .
Remove the second case from the pattern matching. This case is already matched by the last one with s = y, t = []. So the function can be simplified to
let pos_list (list, x) =
let rec pos = function
| ([], x, i) -> i
| (s::t, x, i) -> if s == x then i else pos(t, x, i + 1) in pos(list, x, 0) ;;
Why are you using == (physical equality) instead = which is structural equality? I realize that this might not make a difference if you only have integers but it might yield unexpected behaviour down the road.
See the Comparisons section in the doc: http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html
Pavel Zaichenkov's answer is of course the best one, but you might be interested in knowing the exact cause of the error. Namely, when you have
if y == x then i
without a corresponding else expression, the whole expression is treated as
if y == x then i else ()
where () is the only value of the type unit (and not uint), which is the type of expressions that are evaluated for their side effects only. Since both branches of the if must have the same type, i is deemed to have type unit also. Then, when type-checking the third branch of the pattern-matching, you try to add i and 1, which means that i should have type int, hence the type error.
Related
I want to count how many "u"s are in a list. An example of the function call would be
countu(["u"; "a"; "x"], 0);;
:-int = 1
The code I have is
let rec countu = fun(x, y) ->
if List.length (List.hd x) == 0 then y
else if List.hd x == "u" then countu(List.tl x, y+1)
else countu(List.tl x, y);;
I understand why I'm getting the problem. Ocaml wants a 'a list, but because I am comparing it to a string, it makes it a string. It will also get mad when I recall countu with y+1, because again, it wants a non-specified unit instead of an integer. How do I get around this. I want the signature to look like
val countups : string list * int -> int = <fun>
You have:
if List.length (List.hd x) == 0 then ...
But this only makes sense if x is a list of lists. Your x is a list of strings.
Possibly what you want is just this:
if List.length x = 0 then ...
As a side comment, the equality comparison operator in OCaml is =. The == operator is for special cases, and you shouldn't use it without having a good reason.
I'm new to SML. I've written a function which takes 2 int and a list of tuples as input.
fun move(x,y,mylist:(int * int)list): NOxNO =
let
val counter = ref y-1
in
if y=1 then (x,y)
else (
while !counter > 0 do (
if List.exists (fn s => s = (x,!counter)) mylist
then counter := !counter - 1
else break
);
if !counter = 0 then (x,y) else (x,y-1)
)
end
I may have syntax error since I'm a beginner. What the function is trying to do is: it will check the list to find all the tuples whose first element is x and second element varies from 1 to y-1 (tuples like this: (x,1) (x,2) ... (x,y-1) ) and if all of them exist in the list it will return (x,y) else (x,y-1). I used a while loop and a counter. counter is set to y-1 at first and in while loop if (x,counter) was found, counter's value will decrease. At last if counter=0 it means we have found all the tuples. After running the program I encountered this error:
Caught Error ../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
../compiler/TopLevel/interact/evalloop.sml:44.55
../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
What's wrong?
Here's some feedback:
(Error) As Andreas Rossberg said, break doesn't exist. But if you use (), the loop won't terminate when y > 1 and the predicate evaluates to false. You probably want to "break" by setting counter := 0 or counter := -1, depending on what you want the subsequent if !counter = 0 ... to do.
(Error) As Andreas Rossberg said, ref y-1 gives the following type error:
! Toplevel input:
! val r = ref y-1;
! ^
! Type clash: expression of type
! int
! cannot have type
! int ref
This is because function application (ref y) binds tighter than infix operators (y-1). What you mean is ref (y-1), since you can't subtract 1 from a reference.
This isn't very comprehensible or robust. I tried to run it in the simplest case I could think of,
val test1 = move (1,1,[])
But that's a weird base case not handled by the loop. If I change the numbers slightly,
val test2 = move (5,6,[])
then it returns either (5,6) or (5,5) depending on what you change break into.
Based on your description below the code, here is a suggested implementation, although I'm still not completely certain I understand the use of this function:
(* verticalPointsExist (x, y, ps) checks that
* (x,1), (x,2), ..., (x,y-1) are all in ps. *)
fun verticalPointsExist (_, 0, _) = true
| verticalPointsExist (x, y, ps) = List.exists (fn p => (x,y) = p) ps
andalso verticalPointsExist (x, y - 1, ps)
fun move (x, y, ps) =
if verticalPointsExist (x, y, ps) then (x,y) else (x,y-1)
Considerations I made:
Use recursion rather than iteration.
Split the checking part into a helper function, so move doesn't do two things.
Give the functions good names so the code reads more easily. Since I don't know the domain and am really guessing as to whether y is some kind of vertical dimension, there are probably even better names out there. (verticalLineExists? verticalPathClear?) Maybe a more general function will have a better name, e.g. one that took two points and saw that the line is clear between them.
There is no break in ML. You probably just want to write () there. Also, you'll need parens around the argument to ref in line 3.
I wrote a function that is supposed to receive a list of tuples. I access the components of the tuples with # and the code compiles:
fun recheck ([], n) = []
| recheck (h::t, n) =
if ((#1 h) * (#1 h)) + ((#2 h) * (#2 h)) = n then
h::recheck(t, n)
else
recheck(t, n)
But another function that basically does the same thing, namely receiving a list of tuples and accessing those, causes an error.
fun validate ([]) = true
| validate (h::t) =
if 1 = (#1 h) then
true
else
false
Can't find a fixed record type. Found near #1
What is the difference here and why does the latter cause an error?
Edit
The first function actually does not compile on its own.
But this entire snippet does:
fun drop ([], n) = []
| drop (h::t, 0) = h::t
| drop (h::t, n) =
drop(t, n-1)
fun sts_linear (y, n) =
if y < (Math.sqrt(n)+1.0) then
let
(* x^2 + y^2 = n => x = sqrt(n-y^2) *)
val x = Math.sqrt(n - (y * y));
val xr = Real.realRound(x);
in
if (abs(x - xr) < 0.000000001) then
[(Real.trunc xr, Real.trunc y)]#sts_linear (y+1.0, n)
else
(
[]#sts_linear (y+1.0, n)
)
end
else []
fun recheck ([], n) = []
| recheck (h::t, n) =
if ((#1 h) * (#1 h)) + ((#2 h) * (#2 h)) = n then
h::recheck(t, n)
else
recheck(t, n)
fun sts (n) =
(
let
val pairs = sts_linear(0.0, Real.fromInt n);
in
recheck(drop(pairs, Real.ceil( Real.fromInt (length(pairs))/2.0 ) ), n)
end
)
Your first code doesn't compile, at least with SML/NJ:
If you got it to compile then it must have been in a nonstandard extension of SML.
The problem with both of your definitions is that there is no polymorphic idea of a tuple of arbitrary arity in SML. You can write functions to work on lists of pairs. You can write functions to work on lists of triples. But -- you can't write functions to work simultaneously on lists of pairs and lists of triples (at least if your function tries to do things with these pairs/triples as tuples).
One solution is to get rid of # and use pattern-matching to extract the components:
fun validate [] = true
| validate ((x,y)::t) =
if x = 1 then
true
else
false
But, if you really want to write a function which can polymorphically apply to either lists of pairs or list of triples (or quadruples,...), the easiest thing to do is to represent the pairs, triples, etc. as lists rather than tuples. Lists which contains lists of nonspecified size are not a problem in SML.
Trying to minimize this down, as I have seen the following work in SML/NJ
and i'm not aware of it actually being a compiler extension
val p1 = {x=0, y=0};
val p2 = {x=1, y=1};
val p3 = {x=1, y=1, z=1};
There is an awkward construct from a compiler error perspective
not many languages have errors that work in this fashion,
because the function is valid, but produces a type error
unless an invocation of the function exists to resolve the
type of 'record', thus to resolve the error more code must be added.
fun getFoo(field) = fn record => field record;
Without the following actual calling of the getX
the compiler cannot determine the type of record
of which the complete type information of ALL fields
of the record must be known to the compiler, not just the #x field.
let val getX = getFoo(#x);
val x1 = getX(p1);
val x2 = getX(p2);
val x3 = getFoo(#x)(p3);
in () end;
while the following commented out snippet results in an error because the types of
p1 and p3 are different, and so different invocations of getFoo
are required
(*
let val getX = getFoo(#x);
val x1 = getX(p1);
val x3 = getX(p3);
in () end;
*)
and the following is insufficient since it never resolves the record.
let val getX = getFoo(#x) in () end;
Update: What I want to do with this code is to get a list of dates, year/month/day and a given number as a month, and check to see how many of the dates in the given list are in the same month as that given month. What I meant of x = x + 1 was x++ such as in java or C or C#. As the output I want x. if there is no match, 0 and for any match x = x + 1
So this is my code,
fun number_in_month (Dlist : (int * int * int) list, Month : int, x : int) =
if null Dlist then x
else if #2 (hd Dlist) = Month then x = x + 1 andalso number_in_month (tl(Dlist), Month, x)
else number_in_month ((tl(Dlist)), Month, x)
and it gives me error:
Error: types of if branches do not agree [tycon mismatch]
then branch: int
else branch: bool
in expression:
if null Dlist
then x
else if (fn <rule>) (hd <exp>) = Month
then (x = <exp> + <exp>)
andalso (number_in_month (<exp>,<exp>,<exp>))
else number_in_month (tl <exp>,Month,x)
I really don't get it why sml is considering x = x + 1 of type bool. I'd be really happy if someone could tell me how can I correctly say x = x + 1 in sml.
Thanks a lot in advance.
Saying x = x + 1 in Standard ML, you need to clarify what you intend to say, because clearly x = x + 1 means something you don't intend. What it means is "Compare x with x + 1 and say if they are equal" (which they never will be of any integer).
What I suppose you want to achieve is "update x to its successor", which is not possible without the use of reference types, which I discourage since they are not immutable and functional. The way you usually update something functionally is by passing an updated value to a function that eventually returns it. (Using function arguments as accumulating variables, so it feels as if it's the same variables that update their value e.g. upon each recursive call.)
Another thing I recommend that you do is use pattern matching instead of if-then-else. For example, you know that the list is empty if it matches []. Since the result of your computation is not a boolean, you cannot use "... andalso ..." -- I suspect you do this because you "want to do two things at once, and andalso smells like "doing something and also doing something else", but this would be a misconception. You can do this (using e.g. ; or before), but you would lose your result because these operators deal with side-effects and discard the main effect of one of their operands, so it is not what you want at this point.
Here is my stab in the dark at what you intended, written using pattern matching:
fun number_in_month ([], _, x) = x
| number_in_month ((one,two,three)::dlist, month, x) =
if two = month then number_in_month(dlist, month, x+1)
else number_in_month(dlist, month, x)
Modified: You can also do this without tail-recursion
fun number_in_month([], _) = 0
| number_in_month((_,month1,_)::dlist, month2) =
if month1 = month2 then 1 + number_in_month(dlist, month2)
else number_in_month(dlist, month2)
Or written differently:
fun number_in_month([], _) = 0
| number_in_month((_,month1,_)::dlist, month2) =
(if month1 = month2 then 1 else 0) + number_in_month(dlist, month2)
Or using list combinators:
fun counter(n1,n2) = if n1 = n2 then 1 else 0
fun number_in_month(dlist, month2) =
foldl (fn ((_,month1,_),count) => counter(month1,month2) + count) 0 dlist
Or using reference, as you asked for, even though I discourage this:
fun number_in_month (dlist, month2) =
let val count = ref 0
fun loop [] = !count (* the value inside the ref-cell *)
| loop ((_,month1,_)::dlist) =
if month1 = month2 then (count := !count + 1 ; loop dlist)
else loop dlist
in loop dlist end
As you can see, some complexity is added because I wish to create the ref-cell within the function, but I cannot create a new ref-cell upon every recursive call. So I create a helper function that is recursive and let it have the argument that changes during recursion (it can just inherit month2 and count from the parent scope of number_in_month. When recursion ends (base case), I choose to return the value within the ref-cell (using Standard ML's slightly obscure syntax for dereferencing).
Don't make it a habit of using ref-cells before you master the functional way. Otherwise you are back to coding imperatively in a language that makes this habit ugly. :)
I have been trying to count elements in a list of integer 3-tuples, that equals a given integer using SML, but it's not working. Can anyone help me figure out what's wrong with the below code or straighten it up for me?
fun number_in_month(x : int*int*int list, m: int) =
if null x then 0
else
let fun inc x = x + 1;
in
val counter = 0;
if m = #2 (hd x) andalso m > 0 then inc counter
number_in_month((tl x), m)
` else
number_in_month((tl x), m)
end
This function is supposed to return the number of times m equals to the second element of each tuple in the list.
Clearly you have a hard time to let go of your imperative thinking.
Let me try and address some of your issues
You should be using pattern matching instead of using null x, hd x and tl x.
This also apply to decomposing tuples and records. For example
fun number_in_month ((x1, x2, x3) :: xs, m) = ...
or, since we don't ever use x1 and x3
fun number_in_month ((_, x2, _) :: xs, m) = ...
This way it is clearly seen that the first argument is a list of 3-tuples, and no type annotation
is needed
Also when you omit the explicit type annotation, which is the whole idea of having a type system
that can infer them for you (see next point), then this code
fun foo42 xs = map (fn x => #2 x) xs
will give you some nasty errors on "unresolved flex record" (this error message is from SML/NJ)
/tmp/sml20620PlF:105.5-105.44 Error: unresolved flex record
(can't tell what fields there are besides #2)
which is easily fixed by decomposing the 3-tuple
fun foo42 xs = map (fn (_, x2, _) => x2) xs
Speaking of type annotations. They are (almost always) not needed, and they clutter up the
readability of the code. Not to mention that they unnecessarily restricts the types you function
may be used on.
Also the type annotation you have given is erroneous according to what you really wan't. You
should have places parenthesis around the int * int * int. Currently it is interpreted as a
3-tuple of two ints and an int list int * int * (int list).
If you really insist in type annotating your function, then you can do it like this
val number_in_month : (int * int * int) list * int -> int =
fn ([] , m) => 0
| ((_,x2,_) :: xs, m) => 42
This is "almost" like Haskell, where the type is given just before the function declaration.
Try to be more consistent in they way you indent your code. That will give you better clarity.
Here I'm specifically thinking of the way you have indented the else part end the in ... end
part. The below part is clearly still erroneous in so many ways i can't begin to imagine, but it
gives an idea as how to do it
fun number_in_month(x : int*int*int list, m: int) =
if null x then 0
else
let fun inc x = x + 1;
in
val counter = 0;
if m = #2 (hd x) andalso m > 0 then
inc counter
number_in_month((tl x), m)
else
number_in_month((tl x), m)
end
You can't declare a variable val counter = 0 inside the in ... end part of a let-expression.
The semantics of a let-expression is
let
dec
in
exp_1; ...; exp_n
end
thus all declarations (function and value bindings, etc) must go in the let ... in part.
There is no need on earth to have an increment function, it just clutters the readability.
Remember that SML uses single assignment, thus variables are immutable after they are declared.
The sequence-thing inside your nested if-expression
inc counter
number_in_month((tl x), m)
makes absolutely no sense. The only way you can have more than one expression inside the
then ... else part (actually any place, where a single expression is expected), is with a
sequence (exp_1; ...; exp_n). However this is only usable when all but the last expression has
side effect(s), as their results is ignored/thrown away
- (print "Foo\n"; print "Bar\n"; 42);
Foo
Bar
val it = 42 : int
If you search a bit here on SO, you will see that a quite similar question has recently been asked and answered. Though it differs in the the type of the last argument, you might still get some useful pointers.
All in all a solution might look like
fun number_in_month ([], _) = 0
| number_in_month ((_,x2,_) :: xs, m) =
if x2 = m then
1 + number_in_month(xs, m)
else
number_in_month(xs, m)
However since your problem is simpler than the previously stated one, you could easily use some of the higher-order functions from the list module in the basis library
fun number_in_month (xs, m) = length (List.filter (fn (_, x2, _) => x2 = m) xs)
Or even (arguably) simpler, by folding over the list and incrementing a variable along the way each time it matches
fun number_in_month (xs, m) = foldl (fn ((_, x2, _), b) => if x2 = m then b+1 else b) 0 xs
fun number_in_month (L : (int*int*int) list, m : int) =
if L = nil
then 0
else
(if #2 (hd L) = m then 1 else 0) + number_in_month (tl L,m);
TESTING:
number_in_month ([] , 2);
number_in_month ([(1,2,3)] , 2);
number_in_month ([(1,2,3),(2,2,2)] , 2);
number_in_month ([(1,2,3),(2,2,2),(19,11,29)] , 2);
number_in_month ([(1,2,3),(2,2,2),(19,11,29),(10,28,19)] , 2);
number_in_month ([(1,2,3),(2,2,2),(19,11,29),(10,2,19)] , 2);
number_in_month ([(1,2,3),(2,2,2),(19,11,29),(10,28,19)] , 2);
number_in_month ([(1,2,3),(2,2,2),(19,11,29),(10,28,19)] , 2);
number_in_month ([(1,2,3),(2,2,2),(19,11,29),(10,28,19),(16,2,7)] , 2);
Reference:
http://www.cs.sunysb.edu/~leo/CSE215/smllistexamples.txt
http://www.standardml.org/Basis/list.html