OCaml, Understanding error message - exception

let rec smallest l =
match l with
| [] -> raise Not_found
| [a] -> (fun x -> if x > 0 then x else raise Not_found) a
| h::b::t ->
if h > b then smallest h::t
else smallest b::t`
This function is suppose to take an int list and return the smallest int if there is a positive integer in the list or raise the exception Not_found if there is no positive integer in the list.
When I try this out, I get the following error with smallest h::t found in the third matching pattern underlined:
Error: This expression has type 'a list
but an expression was expected of type int
Can someone explain to me what I am doing wrong?

smallest h::t is equivalent to (smallest h)::t. That is, it applies smallest to the argument h and then prepends it to the list t. This makes OCaml complain that you're producing a list when you're supposed to produce a single integer. What you want is smallest (h::t).
This function is suppose to take an int list and return the smallest int if there is a positive integer in the list or raise the exception Not_found if there is no positive integer in the list.
Even with the above fix, that's not what the function will do. Instead it will find the largest element in the list if there is at least one positive element. That's because you always pick the larger element in your if. If you switch it around, so that it always takes the smaller element, it will fail whenever there's at least one non-positive element in the list.
One way to fix that would be to only pick an element as the new head of the list if it is positive and smaller than the current head or it is positive and the current head is negative.
However another, perhaps cleaner, way to get a function matching your description would be to first define a function that takes the smallest element out of any non-empty list (ignoring whether it's positive or not) and then defining another function that calls the first function after filtering the list to only include the positive elements. Like this:
let smallest_positive xs = smallest (List.filter (fun x -> x > 0) xs)
PS: This isn't related to your problem, but the following expression looks quite strange:
(fun x -> if x > 0 then x else raise Not_found) a
There is usually very little reason in OCaml to create a function only to immediately apply it - that's just a more complicated way to write a let expression and in this case you don't even need the let. In other words, the above is equivalent to:
let x = a in
if x > 0 then x else raise Not_found
Which in turn is equivalent to:
if a > 0 then a else raise Not_found

After some more thought, I was able to answer my own question.
let rec smallest l =
match l with
| [] -> raise Not_found
| [a] -> (fun x -> if x > 0 then x else raise Not_found) a
| h::b::t ->
if h < b && h > 0
then smallest (h::t)
else smallest (b::t)`

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.

Why my Guard doesn't want to call a recursive function in Haskell

i'm trying to call to do recursive in my Haskell program. I want to call my function every time a element of my list is matching with a word.
My code is compiling without probleme but when i'm trying to execute him, i have this eror
haskell: haskell.hs:(27,1)-(30,33): Non-exhaustive patterns in function detect
My function where the problem is :
detect :: [[Char]] -> [[Char]] -> [[Char]]
detect (x:xs) b
| x == "now" || x == "go" = detect xs (SwapP 0 1 b)
| x == "stop" = detect xs (SwapP 0 (length b - 1) b)
detect (x:xs) b = detect xs b
In x:xs is have my list of words, and in my b, i have a function who the job is to change the position of the words.
But the recursive in the guards are not working.
The weirdest thing of my problem is when i'm trying to do the same but outside my guards, it's working, if i'm doing
detect :: [[Char]] -> [[Char]] -> [[Char]]
detect (x:xs) b = detect xs (SwapP 0 (length b - 1) b)
it's working, my first and my last words are changing.
So if anyone have a idea of the problem, you can put a little message. Thanks.
Basically, my problem was my xs list. I was reading all the list recursively and deleting the elements. At the end, my list was without element but my function was still trying to delete & check the content. So, to deal with that, i just added a simple
compares [] b = 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.

Haskell recursive function size that returns the number of elements in a set

Write a recursive function size in haskell that returns the number of elements in a set. Do not use the library function length.
size :: Set a -> Int
This is what i did so far. Does it look right or am i misunderstanding what the question is asking? Thanks
size :: Set a -> Int
size [] = 1
size (_:xs) = 1 + size xs
I think you forgot one important part: the fact that the empty list [] has size 0, so:
size :: Set a -> Int
size [] = 0 -- zero
size (_:xs) = 1 + size xs
Besides code however it is important to be able to explain your code. The first clause can be explained like:
"The size of an empty list is zero (0)".
The recursive clause on the other hand can be explained as:
The size of the non-empty list is the same as one plus the size of a set minus one element (the head).
Note that here, we make the assumption that the type Set a is the same as [a]. This however means that we can have sets with duplicate entries. In case we do not want that, we should use a uniqueness filter. We can use nub :: Eq a => [a] -> [a] for that, or we can implement it in our size function:
size :: Set a -> Int
size = size' []
where size' _ [] = 0
size' l (x:xs) | elem x l = size' l xs
| otherwise = 1 + size' (x:l) xs
One possible solution using higher-order functions:
size :: Set a -> Int
size = sum . fmap (const 1)
This works because Set is an instance of Foldable and can be made an instance of Functor.

Ocaml take function

i am trying to make a function that returns the value of first k elements in a list. This is not working. I do not know why.
Can someone help?
This is the tl function -
let tl j = match j with
| [] -> []
| x :: xs -> xs;;
This is the real take function-
let rec take k xs = function
| [] -> failwith "take"
| x :: xs -> if k = List.length ([x] # xs) then [x] # xs
else [x] # take List.length xs (tl(List.rev.xs))
The cause for the message is that you left out a pair of parentheses, so you're trying to pass List.length as the first parameter to take.
Another problem is that you're defining a function with three parameters – your definition says that take k xs returns a function that takes a list argument (which is unnamed).
A third problem is take (List.length xs) (tl(List.rev xs)).
This attempts to take one more element than there are from the tail of xs (and, for some reason, in reverse).
So I'm going to rewrite it completely.
First of all, you should not use List.length for this.
(List.length is almost never a good solution.)
You only need to care about whether the list is empty or not, it doesn't matter how long it is.
Now, a more formal definition:
take k xs is
if k is 0, it's the empty list
otherwise, if xs is the empty list, it's an error
otherwise, it is the list whose first element is the head of xs, and whose tail is the result of taking k - 1 elements from the tail of xs.
That is,
let rec take k xs = match k with
| 0 -> []
| k -> match xs with
| [] -> failwith "take"
| y::ys -> y :: (take (k - 1) ys)
Your function accepts an integer n, and takes n elements from a list list, which is the list which contains the n first elements of list.
So your signature is likely to be:
int -> 'a list -> 'a list = <fun>
You probably already can guess that the function is going to be defined recursively, so you can already write the definition of your function like this:
let rec take n list = ...
You have to build a list, but let's first consider three major classes of values for n:
n = 0 : just return an empty list
n > 0 : take one element and recurse with n - 1
n < 0 : The negative case is easy to miss, but if you are not cautious, you can easily enter an infinite recursion at runtime with invalid inputs. Here, fortunately, we are going to use an exception and make things terminate down the recursive chain (that's what happens in moldbino's answer, for example), but other functions might not behave as nicely.
Some implementations of take, when given a negative numbers, try to be useful and takes n elements from the end of the list.
Here we will simply treat any n that is not strictly positive as-if if was null.
Null or negative N
When we take zero elements from a list, that means that we return the empty list:
let rec take n list =
if n > 0
then ...
else [];;
Positive N
Now, we consider the case where we take n > 0 elements from a list.
Following the recursive definition of lists, we have to consider each possible kind of lists, namely the empty list and non-empty lists.
let rec take n list =
if n > 0
then
match list with
| [] -> ...
| x :: xs -> ...
else [];;
What happens when we want to take n > 0 elements from an empty list?
We fail.
let rec take n list =
if n > 0 then
match list with
| [] -> failwith "Not enough elements in list"
| x :: xs -> ...
else [];;
Now, the general case of recursion. We have a non-empty list, and n > 0, so we know that we can take at least one element from the list.
This value is x, which forms the head of the list we want to return. The tail of the list is the one made of the n-1 elements of xs, which is easily computed by take itself:
let rec take n list =
if n > 0 then
match list with
| [] -> failwith "Not enough elements in list"
| x :: xs -> x :: (take (n - 1) xs)
else [];;
Your immediate problem is that you need parentheses around (List.length xs). The code also treats an empty input list as an error in all cases, which is not correct. An empty list is a legitimate input if the desired length k is 0.
Update
You also have one extra parameter in your definition. If you say this:
let myfun k xs = function ...
the function myfun has 3 parameters. The first two are named k and xs and the third is implicitly part of the function expression.
The quick fix is just to remove xs.
I think you might be asking for the wrong number of elements in your recursive call to take. Something to look at anyway.