Why is the variable "hd" unbound here? - ocaml

let f x =
match x with
((2, 4)::xr) -> 42
| [(1, y); (_, 3); (_, 4)] -> 5
| [(x, _); (u, w)] -> u + x
| [(44, 11); (12, 3)] -> 42
| (x::xr) -> fst (hd xr)
I've tried running f[(2, 4)] for example.
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

You haven't described the environment you're running in, so it's not really possible to say for sure. But hd is defined in the List module. Most likely you need to write List.hd instead of hd:
# hd;;
Error: Unbound value hd
# List.hd;;
- : 'a list -> 'a = <fun>
#

Jeffrey's answer seems likely. It's worth noting that you can accomplish this without ever calling List.hd by using pattern-matching to bind x to the first element of the head of the tail of the list. The head of the tail otherwise being "the second element in a list which has at least two elements."
let f x =
match x with
(2, 4)::xr -> 42
| [(1, y); (_, 3); (_, 4)] -> 5
| [(x, _); (u, w)] -> u + x
| [(44, 11); (12, 3)] -> 42
| _::(x, _)::_ -> x
Assuming hd was meant to be List.hd in your original code, you may have gotten an exception. Of your previous patterns, only (2, 4)::xr can match a list with one element, and only if that element is (2, 4).
As it is, the code I've shown now features non-exhaustive pattern-matching, and that could generate an exception.

Related

OCaml: create a tuple list from a list using fold_left

How to create a tuple list from one single list, like so:
[1; 2; 4; 6] -> [(1, 2); (4, 6)]
I want to do it using function List.fold_left since I'm trying to learn that currently but don't know how... Is there a way? Or should I leave it like that?
This is a working code that doesn't use List.fold_left:
let rec create_tuple acc l = match l with
| [] -> acc
| x :: y :: l' -> create_tuple (acc # [(x, y)]) l'
| _ -> acc
List.fold_left reads elements one by one. There is no direct way to make it read elements two by two.
It really is pointless complication (great for teaching, though), but if you absolutely want to use List.fold_left here, your accumulator needs to somehow record the state of the traversal:
either you have read an even number of elements so far,
or you have read an odd number and then you have to record what was the last element you read, so that, upon reading the following one, you can pair them.
Here is a way to do it. I use an algebraic datatype to represent the state.
(* This is the type that we’ll use for the accumulator;
the option component is the state of the traversal.
(None, acc) means that we have read an even number of elements so far;
(Some x, acc) means that we have read an odd number of elements so far,
the last of which being x. *)
type 'a accumulator = 'a option * ('a * 'a) list
let folder (state, acc) x =
match state with
| None -> (Some x, acc)
| Some y -> (None, (y,x)::acc)
let create_pairs l =
let (_, acc) = List.fold_left folder (None, []) l in
List.rev acc
Also notice how I avoid the complexity bug that I outlined in a comment: I add elements in reverse order (i.e. at the head of the accumulating list), and at the very end I reverse that list.
#Maëlan's answer is beautiful, but what if we want to get triples rather than pairs? Is there a way we can use List.fold_left to handle this more generically?
let chunks n lst =
let (_, _, acc) = List.fold_left
(fun (counter, chunk, lst') x ->
if counter = n - 1 then
(0, [], List.rev (x :: chunk) :: lst')
else
(counter + 1, x :: chunk, lst'))
(0, [], [])
lst
in
List.rev acc
Using this, chunks 2 [1; 2; 4; 6] returns [[1; 2]; [4; 6]]. We can map this to the result you're looking for with a very simple function that takes a list with two elements and creates a tuple with two elements.
chunks 2 [1; 2; 4; 6] |> List.map (fun [x; y] -> (x, y))
And we get:
[(1, 2), (4, 6)]
This could be used to implement a triples function.
let create_triples lst =
chunks 3 lst |> List.map (fun [x; y; z] -> (x, y, z));;
And now create_triples [1; 2; 3; 4; 5; 6; 7; 8; 9] returns [(1, 2, 3); (4, 5, 6); (7, 8, 9)].
I tried this question(using List.fold_left) and this is the best I could come up with:
type 'a node = First of 'a | Second of ('a * 'a)
let ans =
List.fold_left
(
fun a e ->
match a with
| [] -> (First e)::a
| (First f)::tl -> Second(f, e)::tl
| (Second n)::tl -> (First e)::(Second n)::tl
)
[]
[1; 2; 3; 4; 5; 6; ]
let () =
List.iter
(
fun e ->
match e with
| First f ->
print_endline(string_of_int f)
| Second (f, s) ->
Printf.printf "(%d, %d)" f s
)
(List.rev ans)
Just to make my answer all there...
type 'a node = One of 'a | Two of ('a * 'a)
let ans =
(List.map
(
fun e ->
match e with
| One _ -> failwith "Should only be Two's"
| Two (f, s) -> (f, s)
)
(List.filter
(
fun e ->
match e with
| One _ -> false
| Two _ -> true
)
(List.rev
(List.fold_left
(
fun a e ->
match a with
| [] -> (One e)::[]
| (One o)::tl -> (Two (o, e))::tl
| (Two t)::tl -> (One e)::(Two t)::tl
)
[]
(List.init 10 (fun x -> x + 1))
)
)
)
)
let () =
List.iter
(fun (f, s) -> Printf.printf "(%d, %d) " f s)
ans

Generic types on function don't correspond properly

I have experience with functional programming in general, but I'm new to F#, and I can't get this code to compile no matter what I try:
let group2<'T> (sq: seq<'T>) : seq<'T * 'T> =
Seq.fold (fun (p, l) b -> match p with
| None -> (Some b, l)
| Some v -> (None, (v, b) :: l)) (None, []) sq
I don't understand what this error message is trying to tell me, and I can't for the life of me figure out why it won't compile as-is;
main.fs(2,19): error FS0001: This expression was expected to have type
'seq<'T * 'T>'
but here has type
''a * 'b'
main.fs(4,65): error FS0001: This expression was expected to have type
'seq<'T * 'T>'
but here has type
''a * 'b'
anyone with more F# experience have some advice?
So if you update your code like this
let group2<'T> (sq: seq<'T>) : seq<'T * 'T> =
Seq.fold (fun (p ,l) b -> match p with
| None -> (Some b, l)
| Some v -> (None, (v, b) :: l)) (None, []) sq
|> snd
|> List.rev
|> Seq.ofList
It can work (by removing the state, and converting back from list to sequence). For example
group2 [1;2;3;4]
yields
[(1, 2); (3, 4)]
It's not very idiomatic as it mixes sequences and lists.
A more idiomatic code only for (even) lists:
let rec group2 (xs:'T list) =
match xs with
| [] -> []
| x::y::xs -> ( x, y)::group2 xs
| _ -> failwith "not even"
Basically you deal with 3 choices,
The list is empty, there are no pairs you return an empty list.
There are two items at the start, you pair them in a tuple and process the rest of the list recursively
There's only one item left, we fail because it's not posible to create a tuple with nothing*
If you want to consider odd lists, you can use option types: e.g. None/Some
let rec group2 (xs:'T list) =
match xs with
| [] -> []
| [x] -> [Some x, None]
| x::y::xs -> (Some x,Some y)::group2 xs
Finally you could use the chunkBySize library function for either (even) lists or sequences:
[1;2;3;4]
|> Seq.chunkBySize 2
|> Seq.map (fun a -> a.[0], a.[1])
or
[1;2;3;4]
|> List.chunkBySize 2
|> List.map (fun a -> a.[0], a.[1])

Find max value in list of `(string * int) list`

I have a list of (string * int) list elements and I need to find the biggest int element and return the corresponding(string * int) element.
I have something like this atm, but problem is, I think my approach is more of "typical programming"
let it = [] in
for x = 0 to length LIST - 1 do
let str = ((List.nth LIST x).string) in
let num = ((List.nth LIST x).int) in
let it = it # [num, str] in
let (str, num) = List.hd(List.rev it) in
[str, num]
What I tried to do is to loop through the list and add the string and int value in another list, then sort them, reverse it and then take the head, which should be the max int, then I need to return the pair in (string * int)
Your code is not a well-formed OCaml code. It highlights, however, some number of issues with your understanding of OCaml.
First of all, by default, values in OCaml are immutable. For example,
let x = 0 in
for i = 0 to 10 do
let x = x + 1 in
print_int x;
done
You will get 11111111111 as the output. This is because, during the loop, you are just computing every time the x+1 expression, where x is always 0 and you will always get 1 as the result. This is because, let x = <expr> in <body> is not changing the existing variable x but is creating a new variable x (shadowing any previous definitions) and make it available in the scope of the <body> expression.
Concerning your problem in general, it should be solved as a recursive function greatest_element, which has the following definition,
for an empty list [] it is undefined;
for a list of one element [x] is it is x;
otherwise, for a list of x::xs it is max x (greatest_element xs),
where max x y is x if it is greater or equal to y.
Finally, it looks like you have missed the first steps in OCaml and before solving this task you have to move back and to learn the basics. In particular, you have to learn how to call functions, bind variables, and in general what are the lexical conventions and syntax of the language. If you need pointers, feel free to ask.
First of all, it doesn't seem that you did any kind of sorting in
the code that you provided.
Assuming that your list is of type
(string * int) list then a possible to find the element with the
maximum integer using recursion:
let max_in_list list =
let rec auxiliary max_str max_int = function
| []
-> (max_str, max_int)
| (crt_str, crt_int)::tail when crt_int > max_int
-> auxiliary crt_str crt_int tail
| _::tail
-> auxiliary max_str max_int tail
in
match list with
| []
-> None
| (fst_str, fst_int)::tail
-> Some (auxiliary fst_str fst_int tail)
let check = max_in_list [("some", 1); ("string", 3); ("values", 2)]
You could write a generic maxBy function. This allows you to get the max of any list -
let rec maxBy f = function
| [] -> None
| [ x ] -> Some x
| x :: xs ->
match (maxBy f xs) with
| Some y when (f y) > (f x) -> Some y
| _ -> Some x
(* val maxBy : ('a -> 'b) -> 'a list -> 'a option = <fun> *)
let data = [("a", 3); ("b", 2); ("c", 6); ("d", 1)]
(* val data : (string * int) list = [("a", 3); ("b", 2); ("c", 6); ("d", 1)]*)
maxBy (fun (_, num) -> num) data
(* - : (string * int) option = Some ("c", 6) *)
maxBy (fun (str, _) -> str) data
(* - : (string * int) option = Some ("d", 1) *)
maxBy (fun x -> x) [3; 2; 6; 1]
(* - : int option = Some 6 *)
maxBy (fun x -> x) ["c"; "d"; "b"; "a"]
(* - : string option = Some "d" *)
maxBy (fun x -> x) []
(* - : 'a option = None *)
It can be fun to rewrite the same function in various ways. Here's another encoding -
let maxBy f list =
let rec loop r = function
| [] -> r
| x::xs when (f x) > (f r) -> loop x xs
| _::xs -> loop r xs
in
match list with
| [] -> None
| x::xs -> Some (loop x xs)
(* val maxBy : ('a -> 'b) -> 'a list -> 'a option = <fun> *)

SML, Using foldr to define min of a list

I need to find the minimum value of a list using foldr.
Here’s the code I wrote:
fun minlist nil = nil
| minlist (x::xs) = List.foldr (fn (y,z) => if y < z then y else z) x xs;
However I’m getting an error: “Overloaded > cannot be applied to argument(s) of type ‘a list”
I’ve been stuck for a while. Any help is appreciated
Your first clause says that the minimum value of the empty list is a list.
Thus, (fn (y,z) => if y < z then y else z) produces a list, and y and z must also be lists.
There is no sensible value you can produce for an empty list, so you should either remove that case and live with the compilation warning, or raise an exception.
Finding the minimum of two values
Your expression if y < z then y else z has a built-in name Int.min (y, z).
Dealing with empty lists
You handle the empty list as minlist nil = nil, which means that "the smallest int of an empty int list is the empty list". But the empty list is not an int and so cannot be an element in an int list, or the return value for a function that otherwise returns smallest ints.
As molbdnilo also says, you could either live with a compilation warning (and risk having a Match exception raised at runtime if you ever feed the function an empty list), or raise a specific exception such as Empty when given the empty list. Neither are good, but the latter at least makes the problem clear.
Writing this without foldr it might look like:
fun minimum [] = raise Empty
| minimum [x] = x
| minimum (x::xs) = Int.min (x, minimum xs)
Converting a recursive function to a fold
Given some recursive function foo that depends on some function bar and some default value acc:
fun foo [] = acc
| foo (x::xs) = bar (x, foo xs)
you may notice the similarities between minimum and foo:
acc is x, some minimum value
bar is Int.min.
This is an attempt to generalise the recursion scheme of minimum.
Given the function foldr:
fun foldr f e [] = e
| foldr f e (x::xs) = f (x, foldr f e xs);
you may notice the same similarities:
f is bar, but made into a parameter
e is acc, but made into a parameter
The only thing from minimum that does not fit this general recursion scheme is handling the empty list. So you still have to do that separate from foldr:
fun minimum [] = ...
| minimum (x::xs) = foldr ...
But the rest is similar.
Error-aware return types
A third option would be to change the type signature of the function into
val minimum : int list -> int option
which your current exercise perhaps disallows.
Writing this without foldr it might look like:
fun minimum [] = NONE
| minimum [x] = SOME x
| minimum (x::xs) =
case minimum xs of
NONE => SOME x
| SOME y => SOME (Int.min (x, y))
or better yet:
fun minimum [] = NONE
| minimum [x] = SOME x
| minimum (x::xs) = Option.map (fn y => Int.min (x, y)) (minimum xs)
Converting this function to use foldr is the same process, but with a different f.
Tail recursion
The minimum function without folding (repeated from above):
fun minimum [] = raise Empty
| minimum [x] = x
| minimum (x::xs) = Int.min (x, minimum xs)
has a problem being that it mainly uses stack memory.
This can be illustated by evaluating the function by hand:
minimum [1,2,3,4,5]
~> Int.min (1, minimum [2,3,4,5])
~> Int.min (1, Int.min (2, minimum [3,4,5]))
~> Int.min (1, Int.min (2, Int.min (3, minimum [4,5])))
~> Int.min (1, Int.min (2, Int.min (3, Int.min (4, minimum [5]))))
~> Int.min (1, Int.min (2, Int.min (3, Int.min (4, 5))))
~> Int.min (1, Int.min (2, Int.min (3, 4)))
~> Int.min (1, Int.min (2, 3))
~> Int.min (1, 2)
~> 1
Since the outer Int.min cannot be calculated before the recursive call has returned, the amount of stack memory used to compute the function grows proportional to the length of the list.
You can avoid this by using an accumulating argument:
fun minimum [] = raise Empty
| minimum (y::ys) =
let fun helper [] acc = acc
| helper (x::xs) acc = helper xs (Int.min (x, acc))
in helper ys y end
Evaluating this function by hand:
minimum [1,2,3,4,5]
~> helper [2,3,4,5] 1
~> helper [3,4,5] (Int.min (2, 1))
~> helper [3,4,5] 1
~> helper [4,5] (Int.min (3, 1))
~> helper [4,5] 1
~> helper [5] (Int.min (4, 1))
~> helper [5] 1
~> helper [] (Int.min (5, 1))
~> helper [] 1
~> 1
Since Int.min is commutative, you might as well solve this exercise with foldl instead of foldr in the exact same way as you would have above, and you'd have a tail-recursive variant that uses less stack space.

pairing an int with a list of ints in OCaml

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)]