I am trying to create a tree from an int list in OCAML. I am very new to functional programming. This is my function so far:
let rec theList (lst : int list) =
match lst with
| [] -> Empty
| h::t -> insert Empty h::theList List.tl lst
when insert is a function that creates a node and puts the value of h in the node. I try to traverse through the list but at the colons after I call insert with the arguments I get the error: "Error: The variant type bstTree has no constructor ::" as this a type I defined as:
type bstTree = Empty | bstTree * Node of int * bstTree
In a broad sense all I am trying to do is recurse through the list and call insert on each int in the list. I have been working on this for awhile now so any help is appreciated, thank you.
There are many problems with your code (to be expected if you're just starting out).
First, your type definition is not syntactically valid:
# type bstTree = Empty | bstTree * Node of int * bstTree;;
Error: Syntax error
Most likely you want something more like this:
type bstTree = Empty | Node of bstTree * int * bstTree
Second, you're defining a function named theList, but inside the function you call a function named fromList. I have a suspicion that these are supposed to be the same name.
Third, there is no need to call List.tl since you have already matched the tail of the list under the name t.
Fourth, you are going to need more parentheses in your expression. A good starting point might be something like this:
insert Empty h (fromList List.tl lst)
As the compiler is pointing out, you can't apply the constructor :: to values of type bstTree. The :: constructor only works for building a list from an element and another (smaller) list.
Related
i have to do a program in ocaml that a Node with a string and a int
is my first program in ocaml and in the web there isn't a lot of information
type tree = string*exp*tree*tree ;;
type exp = Etree of tree | Int of int ;;
let eval (e:exp) =
match e with
| []->[]
| Int _ -> e
| Etree(n) -> match n with
| Node(s, i, t1, t2) -> eval i
;;
let t : Etree = Node("a", Int 1, Empty, Empty)
eval t;;
the IDE tell me that:
Type exp defined.
Toplevel input:
| Int _ -> e
^^^^^
This pattern matches values of type exp,
but should match values of type 'a list.
Toplevel input:
let t : Etree = Node("a", Int 1, Empty, Empty)
^
Syntax error.
can someone tell me why?
The line | []->[] in your pattern matching makes the compiler believe that e is a list. You should remove that line (why do you have it in the first place?).
This won't be enough to correct the problem, as you use that Node constructor that you didn't declare. You should change your declaration of tree.
Now one other problem is that tree references exp even though exp hasn't been declared yet. That's problematic.
So, you should change your initial types declaration to:
type tree = Node of string * exp * tree * tree
and exp = Etree of tree | Int of int ;;
Note the use of the and keyword before exp. That tells the compiler that the two type definitions are mutually recursive (that is, they mention each other).
Your second problem comes from the fact that types and constructors are two different things.
Types are an annotation on value, they are lowercase and on the left of the = in type declarations.
Constructors are values, they are Uppercase and on the right of the = in type declarations.
exp is a type, Etree is one of its constructor.
So your declaration of the value t should be
let t : exp = Etree( Node("a", Int 1, Empty, Empty) )
At this point, the compiler will complain about Empty (and rightfully so) because Empty is not part of your tree definition. Just the constructor to tree and you should be fine.
It looks to me like there are several issues with your types.
The error message you receive is because you try to match e, which has type exp, to the pattern []. But [] is an empty list and not a constructor of exp. If you want to have emptry expressions you need to provide a seperate constructor for that. For example
type exp = Etree of tree | Int of int | Nothing;;
Additionally you later seem to want to provide an Empty tree to the tree t. I would expect you to get another error there because again Empty is not a value of type tree. Lastly I think you want to give the term t the type exp and not Etree beause Etree is a constructor for expressions and not a type.
Some functions in the List module fail when the argument is an empty list. List.rev is an example. The problem is the dreaded Value Restriction.
I met the same problem while trying to define a function that returns a list with all but the last element of a list:
let takeAllButLast (xs: 'a list) =
xs |> List.take (xs.Length - 1)
The function works well with nonempty lists, but a version that would handle empty lists fails:
let takeAllButLast (xs: 'a list) =
if List.isEmpty xs then []
else xs |> List.take (xs.Length - 1)
takeAllButLast []
error FS0030: Value restriction. The value 'it' has been inferred to have generic type
val it : '_a list, etc.
I tried several things: making it an inline function, not specifying a type for the argument, specifying a type for the returned value, making the function depend on a type argument, and using the Option type to obtain an intermediate result later converted to list<'a>. Nothing worked.
For example, this function has the same problem:
let takeAllButLast<'a> (xs: 'a list) =
let empty : 'a list = []
if List.isEmpty xs then empty
else xs |> List.take (xs.Length - 1)
A similar question was asked before in SO: F# value restriction in empty list but the only answer also fails when the argument is an empty list.
Is there a way to write a function that handles both empty and nonempty lists?
Note: The question is not specific to a function that returns all but the last element of a list.
The function itself is completely fine. The function does not "fail".
You do not need to modify the body of the function. It is correct.
The problem is only with the way you're trying to call the function: takeAllButLast []. Here, the compiler doesn't know what type the result should have. Should it be string list? Or should it be int list? Maybe bool list? No way for the compiler to know. So it complains.
In order to compile such call, you need to help the compiler out: just tell it what type you expect to get. This can be done either from context:
// The compiler gleans the result type from the type of receiving variable `l`
let l: int list = takeAllButLast []
// Here, the compiler gleans the type from what function `f` expects:
let f (l: int list) = printfn "The list: %A" l
f (takeAllButLast [])
Or you can declare the type of the call expression directly:
(takeAllButLast [] : int list)
Or you can declare the type of the function, and then call it:
(takeAllButLast : int list -> int list) []
You can also do this in two steps:
let takeAllButLast_Int : int list -> int list = takeAllButLast
takeAllButLast_Int []
In every case the principle is the same: the compiler needs to know from somewhere what type you expect here.
Alternatively, you can give it a name and make that name generic:
let x<'a> = takeAllButLast [] : 'a list
Such value can be accessed as if it was a regular value, but behind the scenes it is compiled as a parameterless generic function, which means that every access to it will result in execution of its body. This is how List.empty and similar "generic values" are implemented in the standard library.
But of course, if you try to evaluate such value in F# interactive, you'll face the very same gotcha again - the type must be known - and you'll have to work around it anyway:
> x // value restriction
> (x : int list) // works
Recently, I started learning F# and I am struggling to work with discriminated unions, lists en structures. I'd found an exercise where I need to do the following:
'Define a NonEmptyList<'a> data structure which can represent a list which can never be empty'
Attempt
let NonEmptyList (input : List<'a>) =
match input with
| [] -> failwith "List canot be empty"
| [x] -> x
Not really sure if this is correctly implemented with the let-keyword. I.e... do I need this construction perhaps:
type NonEmptyList<'a> = struct
| List
edit 1
type NonEmptyList<'T> =
| Cons of 'T * List<'T>
| Single of List<'T>
edit 2
let list1 : NonEmptyList<'T> = Single[1..10]
let list2 : NonEmptyList<'T> = Cons([1..3],[1..3])
I am receiving a parser error: This construct causes code to be less generic than indicated by the type annotations. The type variable 'T has been constrianed to be type 'a list.
First of all, my reading of the task is to give a type definition (using type) rather than a function that checks whether a list is empty.
To solve this, it's best to first understand normal F# lists:
type List<'T> =
| Cons of 'T * List<'T>
| Empty
Here, a list is either empty (represented by the Empty value) or it contains a value of type 'T followed by another list represented by List<'T>. This way, you can create:
let nop = Empty // Empty list
let oneTwo = Cons(1, Cons(2, Empty)) // List containing 1 and 2
So, to answer the question, you will need a very similar definition to the one for List<'T>, except that it should not be possible to create an Empty list. You can start with something like this:
type NonEmptyList<'T> =
| Cons of 'T * NonEmptyList<'T>
Now that I removed Empty, we can no longer create empty lists - but this does not quite do the trick, because now you can never end any list. I won't give a full answer to avoid spoilers as I think figuring this out is the point of the exercise, but you will need something like:
type NonEmptyList<'T> =
| Cons of 'T * NonEmptyList<'T>
| // One more case here
What can the last case be, so that it does not contain another List<'T> (and thus lets us end a list), but is not Empty, so that we cannot create empty lists?
A non-empty list consists of a head and an optional non-empty tail. You can represent such a type as a single-case union:
type NEL<'a> = NEL of 'a * NEL<'a> option
let l = NEL(1, Some(NEL(2, None)))
or a record type:
type NEL<'a> = {head : 'a; tail : NEL<'a> option}
let l = { head = 1; tail = Some({head = 2; tail = None})}
First of all I usually programming in imperative languaes, that makes me hard to explain certain things. First of all is functions without args, and return types. Example is function that flattens a list:
# let rec flat = function
[] -> []
| h :: t -> h # flat t;;
val flat : 'a list list -> 'a list = <fun>
How OCaml interpreter know that:
My function flat need exactly one argument which is "list of lists".
Flat returns type is a list. Do the interpreter checks it with [] -> [] line?
let rec flat = function
[] -> []
| h :: t -> h # flat t;;
You used function keyword. function is a shortcut for match ... with. So the function you wrote is exactly like
let rec flat l =
match l with
[] -> []
| h :: t -> h # flat t
That's why ocaml knows your function has one parameter
Your function is recursive. [] -> [] is the basic case and it is also where the function will be stopped. And yes, interpreter checks it with [] -> [].
Furthermore, a function must have at least a unit parameter which is () or a normal parameter. If a function does not have anything, it is not a function, instead, it is a variable with a fixed value.
Let's have an example:
let f1 = Random.int 10;
f1 does not have any parameter, even without a () (here () is just like a method in Java without any parameter). Then f1 is a constant value which was generated by the Random. No matter when you call it, f1 will always be fixed.
let f2 () = Random.int 10;
f2 is a function. And each time you call f2(), the Random inside will generate a random in and returns it.
let rec flat = function
[] -> []
| h :: t -> h # flat t;;
Let's go through this a step at a time. The function keyword, as you might expect, gives a function. The basic syntax is function | pat1 -> branch1 | pat2 -> branch2, and what you get is a function of one argument that tries to match that argument against each pattern in turn, and for the first pattern that matches the result is the corresponding branch.
So that's how we know flat is a function. Moreover, we can see that its one argument is matched against [], which is a list. So flat must be a function that takes a list. We see that if the input is [] then the output is [], so it's a function that takes a list and returns a list.
Now let's look at that second pattern. h :: t is a pattern that matches a list and creates two new variable bindings: h is the first element of the list and t is all the rest of the elements. In particular, h has whatever type the elements of the input list have.
If you look at what happens if this pattern match succeeds, h # flat t, we see the list concatenation operator # applied to h and flat t. This means that h must be a list, and must be the same kind of list as flat t. So the elements of the input list are lists, and so is the output of the function.
This gives you flat : 'a list list -> 'a list.
To answer your questions directly, flat needs exactly one argument because it is defined with the function keyword and the return values of the branches are values and not functions (if the function branches were also functions, that would meant flat could have two or more arguments). It is a list because the pattern match is against list constructors, and it is a list of lists because h is an element of the list and is used with the # operator, which requires its arguments to be lists, so the elements of the list are lists.
There are actually three reasons why the return type must be a list:
In the first branch, a list [] is returned.
In the second branch, the result of # is returned, and # returns lists
Also in the second branch, flat t is called recursively, and then given as an argument to #. Since it is an argument to #, it must be a list, and so flat must return a list.
The third bullet point is especially interesting, because it shows you that it's not just how you create values that determines their type, but how you use them as well.
I am new to Ocaml and have defined nested lists as follows:
type 'a node = Empty | One of 'a | Many of 'a node list
Now I want to define a wrapping function that wraps square brackets around the first order members of a nested list. For ex. wrap( Many [ one a; Many[ c; d]; one b; one e;] ) returns Many [Many[one a; Empty]; Many[Many[c;d]; Empty]; Many[b; Empty]; Many[e; Empty]].
Here's my code for the same:
let rec wrap list = function
Empty -> []
| Many[x; y] -> Many [ Many[x; Empty]; wrap y;];;
But I am getting an error in the last expression : This expression has the type 'a node but an expression was expected of the type 'b list. Please help.
Your two matches are not returning values of the same type. The first statement returns a b' list; the second statement returns an 'a node. To get past the type checker, you'll need to change the first statement to read as: Empty -> Empty.
A second issue (which you will run into next) is that your recursive call is not being fed a value of the correct type. wrap : 'a node -> 'a node, but y : 'a node list. One way to address this would be to replace the expression with wrap (Many y).
There will also be in issue in that your current function assumes the Many list only has two elements. I think what you want to do is Many (x::y). This matches x as the head of the list and y as the tail. However, you will then need a case to handle Many ([]) so as to avoid infinite recursion.
Finally, the overall form of your function strikes me as a bit unusual. I would replace function Empty -> ... with match list with | Empty -> ....