I have an (int * string) tuple which I want to covert into a list. The tuple is of the form (N, E) where is N is the number of occurances of element E.
The function should return a list with N occurences of E in it. Example is below. Lets assume this function is called tuple_decode.
tuple_decode (1, "A") -> ["A"]
tuple_decode (2,"B") -> ["B";"B"]
tuple_decode (4,"C") - > ["C";"C";"C";"C"]
The tuple_decode function is as follows
let tuple_decode acc (n,elem) =
let add_one_elem i =
match i with
0 -> acc
| i -> elem :: acc ; add_one_elem (i-1) (* Line 184 *)
in
add_one_elem n
;;
when I try to compile this function I get the following error.
File "all_code.ml", line 184, characters 11-22:
Warning 10: this expression should have type unit.
File "all_code.ml", line 184, characters 25-37:
Error: Unbound value add_one_elem
Could someone help me figure out why I get this error and warning.
Regards
Puneet
The warning comes from sequence composition using ;. When you write S1 ; S2, the compiler expects S1 to have unit type. But here S1 returns a list (elem::acc) whose value will be thrown away. Moreover, since you didn't pass acc as an argument, its value doesn't change after all recursive calls.
The error is due to recursive use of add_one_elem. Because you didn't use rec keyword, when add_one_elem (i-1) is called, OCaml doesn't know add_one_elem is being recursively defined.
Moreover, acc should be a parameter of add_one_elem to accumulate results:
let tuple_decode (n, elem) =
let rec add_one_elem i acc =
match i with
| 0 -> acc
| i -> add_one_elem (i-1) (elem::acc)
in add_one_elem n []
As #pad has already answered your question sufficiently, a nice solution would also be:
let decode (n, elem) = List.init n (fun _ -> elem)
Related
As I am going through the website:
http://www.cs.princeton.edu/courses/archive/fall14/cos326/sec/03/precept03_sol.ml
I have got a question according to the Ocaml structure. To be more specific, I have questions according to the code:
let rec reduce (f:'a -> 'b -> 'b) (u:'b) (xs:'a list) : 'b =
match xs with
| [] -> u
| hd::tl -> f hd (reduce f u tl);;
What does the f hd do at the very last line? (I understand that reduce f u tl is calling the function itself again.)
My second question is how to use a function to implement another function in Ocaml. For the code:
let times_x (x: int) (lst: int list) : int list =
map (fun y -> y*x) lst
What does fun y -> y*x do? what does lst do at the end of the code?
Thank you for the help!
The code that has been provided is a reduce function that takes three parameters - a function that maps inputs of type 'a and 'b to an output of type 'b, a value of type 'b, and as list of elements of type 'a.
For example, the length example from the lecture:
let length (lst: int list) : int =
reduce (fun _ len -> len + 1) 0 lst
The first parameter to reduce is a function that, when given two parameters, discards the first one and returns the second parameter incremented by one. The second is a value (0) to be used as an accumulator. The third is a list to find the length of.
The behavior of this recursive reduce function is to return the second parameter (an accumulator as used in the length example) once the provided list is empty, and otherwise run the provided function using the head of the list and the recursed value.
Once again going to the length example, say we give it a list with a single element [1].
Our call to length becomes reduce (fun _ len -> len + 1) 0 [1]
Recall reduce:
let rec reduce (f:'a -> 'b -> 'b) (u:'b) (xs:'a list) : 'b =
match xs with
| [] -> u
| hd::tl -> f hd (reduce f u tl);;
First, we match [1] against [], which fails. Since it is a non-empty list, we run f hd (reduce f u tl)
Recall that f is the parameter that length provided: fun _ len -> len + 1
Therefore, we effectively run the following:
(fun _ len -> len + 1) 1 (reduce (fun _ len -> len + 1) 0 [])
In this case, the length function discards the first parameter since the values in the list are not necessary to know the length of the list.
The recursive portion will match against [] and return the value of u at the time, which is 0.
Therefore, one level up, (fun _ len -> len + 1) 1 (reduce (fun _ len -> len + 1) 0 []) becomes (fun _ len -> len + 1) 1 0 and returns 0 + 1, simplifying to our expected value 1, which represents the length of the list.
Now, to your second question, in regards to times_x. This performs a mapping. For example, we can map [1;2;3;4;5] to [3;6;9;12;15] with a mapping fun x -> x * 3.
Here times_x is defined as follows:
let times_x (x: int) (lst: int list) : int list =
map (fun y -> y*x) lst
times_x takes an integer and a list. Using the above example, we could call it with times_x 3 [1;2;3;4;5] to get [3;6;9;12;15].
Beyond this I recommend looking into how map and reduce functions work in general.
I hope this answer was adequate at addressing your question.
Im trying to add a tuple of type (int*int) on a for cycle to a list but i get an error saying : this expression should have type unit.
this is what i have right now:
let addtuple k lst =
for i=0 to k - 1 do
let (n,j) =Scanf.scanf " %d %d" (fun a b->(a,b))
in
(n,j)::lst
done;;
The purpose of the OCaml for is to do something, rather than compute a value. So the body of the loop should be an OCaml expression that has a useful side effect (like printing a value). For this reason, the body of a for loop should have the type unit, the type used for expressions that don't have an interesting value. But your loop has a body that is a list. The compiler is telling you (correctly) that this indicates that something is wrong.
Your code is written assuming that the expression (n, j) :: lst will change the value of lst. But this is not the case. In a functional language like OCaml, you can't change the values of variables.
If your function is supposed to return a list, it can't be based on a for loop, which always returns () (the unique value of type unit). Most likely it should be based on a fold (which accumulates a value while working through a series of inputs) or on your own recursive function.
With a for you need to use ref:
let addtuple k lst =
let r = ref lst in
for i = 1 to k do
r := (Scanf.scanf " %d %d" (fun x y -> (x, y))) :: !r
done;
!r;;
A more functional approach using a recursive function:
let rec addtuple k lst =
match k with
| 0 -> lst
| _ -> addtuple (k - 1) ((Scanf.scanf " %d %d" (fun x y -> (x, y))) :: lst);;
let list_min_fold = List.fold (fun acc -> List.min acc ) 0 lst
printfn"Using regular List.fold function:\n The minimum is: %A\n"
(list_min_fold)
When I execute my code this error displays:
error FS0001: The type '('a -> 'b)' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface
Why? Please help :(
Are you trying to find the smallest number in a list? If so, you need to use the min function (which takes just two arguments) rather than List.min (which takes a list of arguments):
To keep the code the most similar to your example, you can write (note also that starting with 0 is not going to work, so I used System.Int32.MaxValue instead):
let lst = [4;3;1;2;5;]
let list_min_fold = List.fold (fun acc -> min acc) System.Int32.MaxValue lst
It is also worth noting that the function you pass to fold takes two arguments - the state acc and the current value:
let list_min_fold = List.fold (fun acc v -> min acc v) System.Int32.MaxValue lst
But thanks to partial function application you can omit one of them (as you did), or both of them:
let list_min_fold = List.fold min System.Int32.MaxValue lst
as always Tomas answer is spot on so I have but a small remark:
as you probably saw it makes no sense to try to find the minimum of an empty list (so the function probably should be of type 'a option and when you have an non-empty list it's very easy to use List.reduce (which is basically just a fold for binary operations and min is a great candidate for such an operation):
let list_min xs =
match xs with
| [] -> None
| _ -> List.reduce min xs
|> Some
this way you get:
> list_min [2;1;5;3];;
val it : int option = Some 1
> list_min [2;1;5;3;0];;
val it : int option = Some 0
> list_min ([] : int list);;
val it : int option = None
ok it's a fair point that the question was about fold - so if it has to be exactly List.fold you can of course do (as TheInnerLight remarked):
let list_min xs =
match xs with
| [] -> None
| (x::xs) -> List.fold min x xs
|> Some
(* function for union of two ordered sets*)
let rec search n list1 = match list1 with
[] -> false
| head :: tail when head = n -> true
| head :: tail when head != n -> search n tail
;;
(* function calls and output *)
Printf.printf("\nList = {");;
open Printf
let list1=[3;1;2;4];; (* Input first set here *)
let () = List.iter (printf " %d ") list1;;
printf("}");;
n=2;;
let u = search n list1;;
I am getting an error:
File "search.ml", line 15, characters 0-1:
Error: Unbound value n
Line 15 => "n=2;;"
Kindly inform whether it is a syntactic error or otherwise and possible remedy as well. Implementation is done on linux.
Expression n=2 compares n to 2, however n is not defined yet, so you get an error. You should use let n = 2 to bind values to names.
in OCaml to bound a value with a name one should use len name = value syntax
I am using OCaml to write a function that takes a list of ints and an int element and returns a list of pairs where the first element of every pair is the int element and the second element of the pair is a member from the list. For example, let say I have the number 1 and the list [10; 20; 30] as inputs. I like the function to return [(1, 10); (1, 20); (1, 30)]. I wrote the following function:
let rec f (lst : int list) (elm : int) : (int*int) list =
match lst with
| [] -> failwith "empty list"
| [x] -> [(x, elm)];;
I am getting the following error:
Characters 59-120:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
_::_::_ val f : int list -> int -> (int * int) list = <fun>
What am I missing?
Here is your code
let rec f (lst : int list) (elm : int) : (int*int) list =
match lst with
| [] -> failwith "empty list"
| [x] -> [(x, elm)]
In your match, you listed two cases: [] and [x].
Your first case is [], you mean empty, no problem.
Your second case is [x], what did you want to mean? In OCaml, it means a list with only one element.
How about the cases where there are more than one element?
For any if else or match with, you should include all cases.
When you fix this problem, you will soon find you really missed something more there.
Here is the correct code:
let rec f e l =
match l with
| [] -> []
| x::[] -> [(e,x)]
| x::tl -> (e,x)::(f e tl)
Note
above code is not tail-recursive and you normally should consider about it, I will leave that to you.
you don't need ;; if you write your code in file and compile the file
You don't need to declare types in most cases and that is one of the best thing ocaml has.
Your patterns match lists of length 0 ([]) and of length 1 ([x]). The compiler is telling you that there are other lengths that a list might have, so your pattern is probably wrong (which is true).
I might note that it's not an error to get an empty list as an argument. Thinking this way will make it much harder to answer the problem. If you get an empty list, the correct answer is an empty list of pairs.
let rec f e = function
| [] -> []
| x::tl -> (e,x)::f e tl
Or
let f e = List.map (fun x -> (e,x))
Test
# f 1 [];;
- : (int * 'a) list = []
# f 1 [10;20;30];;
- : (int * int) list = [(1, 10); (1, 20); (1, 30)]