expression has type 'a list -> 'b list but an expression was expected of type 'b list - functional-programming

This is my function
let rec helper inputList = function
| [] -> []
| a :: b :: hd ->
if a = b then helper ([b::hd])
else a :: helper (b::hd)
It's not complete, however I can't see why I keep getting the error in the title at helper ([b::hd]). I've tried helper (b::hd) or helper (b::hd::[]) however all come up with errors. How do I make it so that it works?

When you use function you are supplying a pattern for the parameter of the function. But you already have a parameter named inputList. So this function helper is expecting two parameters (but it ignores the first).
You can fix this by removing inputList.
You also have a problem in your first recursive call to helper. Your expression [b :: hd] is a list of lists. I suspect that you want something more like just b :: hd here.
There is at least one other problem, but I hope this helps get you started.

There are multiple errors here. One is that the keyword function means we have an implicit parameter over which we are working. So the pattern matching happens on that "invisible" parameter. But here you defined probably the explicit one: inputList. So we can remove that one:
let rec helper = function
| [] -> []
| a :: b :: hd -> if a = b then helper ([b::hd]) else a :: helper (b:: hd)
Next there is a problem with the types: in the recursion, you use:
helper ([b::hd]); and
a :: helper (b:: hd)
But you put these on the same line, and that makes no sense, since the first one passes a list of lists of elements, and the second a list of elements. So the result of the first one would be a list of list of elements, and the second one a list of elements. It does not make sense to merge these.
If I understood correctly that you want to ensure that no two consecutive elements should occur that are equal, then we should rewrite it to:
let rec helper = function
| [] -> []
| a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)
You have defined two patterns here:
one for the empty list; and
one for a list with at least two elements.
The second one will perform recursion on the tail of the list b :: hd. So that means that eventually when we pass it a list with n elements, it will recursively work on a list with n-1 elements, n-2 elements, etc. But eventually it will have one element. And there is no case for that. So we need to add a case for the one element pattern:
let rec helper = function
| [] -> []
| h :: [] -> h :: []
| a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)

Related

F# define search function

I am new to F# and am having trouble with my code. Its a simple problem to define a function, search, with that take a boolean function and a list and return an index. So for example:
> search (fun x -> x > 10) [ 2; 12; 3; 23; 62; 8; 2 ];;
val it : int = 1
> search (fun s -> s < "horse") [ "pig"; "lion"; "horse"; "cow"; "turkey" ];;
val it : int = 3
What I have as of right now finds the right match but what I cant figure out is how to return a number instead of the rest of the list. I know I'm getting the list instead of a value back because I wrote "if f head then list". What I don't know is what I should put there instead or if what I have is not going to get the result I want.
Below is the code I have written.
let rec search f list =
match list with
| [] -> [-1]
| head::tail ->
if f head then list
else search f tail
Returning a number is easy, you just... return it. Your problem is that you don't have a number to return, because you can't derive it directly from the current state. You have to keep track of the number yourself, using some internal state variable.
When using recursion you change state by calling your function recursively with "modified" arguments. You're already doing that with the list here. To keep internal state in a recursive function you have to introduce another argument, but not expose it outside. You can solve that by using an internal recursive helper function. Here's one that keeps track of the previous item and returns that when it encounters a match:
let search f list =
let rec loop list prev =
match list with
| [] -> None
| head::tail ->
if f head then prev
else loop tail (Some head)
in
loop list None
That's a silly example, but I don't want to just solve your homework for you, because then you wouldn't learn anything. Using this you should be able to figure out how to keep a counter of which position the current item is in, and return that when it matches. Good luck!
You typically define an inner recursive function to help you carry state as you loop, and then call the inner function with an initial state.
let search predicate list =
let rec loop list index =
match list with
| [] -> -1
| head::tail ->
if predicate head then index
else loop tail (index + 1)
loop list 0

Tree to ordered list with tail recursion

I am actually sitting over a hour on a problem and donĀ“t find a solution for it.
I have this data type:
type 'a tree = Empty | Node of 'a * 'a tree * 'a tree
And i have to find a function which converts a given tree in a ordered list. There is also no invariant like that the left child has to be less then the right. I already found a "normal" recursion solution but not a tail recursive solution. I already thought about to build a unordered list and sort it with List.sort, but this uses a merge sort which is not tail recursive. Maybe someone has a good advice.
Thank you!
If you want to traverse the tree in order and return a list, that means our function inorder must have the type 'a tree -> 'a list.
let rec inorder t =
match t with
| Empty -> []
| Node (v, l, r) -> List.append (inorder l) (v :: (inorder r)) (* ! *)
However List.append is in tail position, not inorder. Another problem is we have two calls to inorder. If we put inorder l in tail position, inorder r could not possibly be in tail position - and vice versa.
A neat way to work around this problem is continuation passing style. We take our function above and convert it into a helper function with an extra parameter for our continuation, return
(* convert to helper function, add an extra parameter *)
let rec loop t return =
match t with
| Empty -> ...
| Node (v, l, r) -> ...
The continuation represents "what to do next", so instead of sending values directly out of our function, we must hand them to the continuation instead. That means for the Empty case, we'll return [] - instead of simply []
let rec loop t return =
match t with
| Empty -> return []
| Node (v, l, r) -> ...
For the Node (v, l, r) case, now that we have an extra parameter we can write our own continuation that informs loop what to do next. So to construct our sorted list, we will need to loop l, then loop r (or vice versa), then we can append them. We'll write our program just like this.
let rec loop t return =
match t with
| Empty -> return []
| Node (v, l, r) ->
loop l ... (* build the left_result *)
loop r ... (* build the right_result *)
return (List.append left_result (v :: right_result))
In this next step, we'll fill in the actual lambda syntax for the continuations.
let rec loop t return =
match t with
| Empty -> return []
| Node (v, l, r) ->
loop l (fun left ->
loop r (fun right ->
return (List.append left (v :: right))))
Last, we define inorder which is a call to loop with the default continuation, identity.
let identity x =
x
let inorder t =
let rec loop t return =
match t with
| Empty -> return []
| Node (v, l, r) ->
loop r (fun right ->
loop l (fun left ->
return (List.append left (v :: right))))
in
loop t identity
As you can see loop r (fun right -> ...) is in tail position for the Node branch. loop l (fun left -> ...) is in tail position of the first continuation. And List.append ... is in tail position of the second continuation. Provided List.append is a tail-recursive procedure, inorder will not grow the stack.
Note using List.append could be a costly choice for big trees. Our function calls it once per Node. Can you think of a way to avoid it? This exercise is left for the reader.

Does this code have a mistake?

I am just reading about syntax of Erlang, and read this implementation of while loop:
-module(helloworld).
-export([while/1,while/2, start/0]).
while(L) -> while(L,0).
while([], Acc) -> Acc;
while([_|T], Acc) ->
io:fwrite("~w~n",[Acc]),
while(T,Acc+1).
start() ->
X = [1,2,3,4],
while(X).
Is the semicolon a mistake? (4th line: while([], Acc) -> Acc;)
I would write the two functions like this:
while(L) -> while(L,0).
while([], Acc) -> Acc;
while([_|T], Acc) ->
io:fwrite("~w~n",[Acc]),
while(T,Acc+1).
start() ->
X = [1,2,3,4],
while(X).
Using whitespace to separate the function definitions makes it clear that two different functions are being defined: while/1 and while/2.
I had no idea about [_|T]. It just comes after this part in the
tutorial, so that's very confusing.
That's nearly equivalent to [H|T], which deconstructs a list into the Head and the Tail, where the Head is the first element of a list and the Tail is the rest of the list. The variable name _ means that you don't care about the variable, so you will not use it in the function body. In this case, it means that you don't care about the Head of the list, all you want is the Tail of the list. If a named variable is used in the head of a function clause, and you don't use the variable in the body of the function, then the compiler will give you a warning.
Here's an example of how deconstructing a list with pattern matching works:
-module(my).
-compile(export_all).
f([Head|Tail]) ->
io:format("The head of the list is: ~w~n", [Head]),
io:format("The tail of the list is: ~w~n", [Tail]).
In the shell:
8> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
9> my:f([1, 2, 3]).
The head of the list is: 1
The tail of the list is: [2,3]
ok
10>
No. There are two functions defined here: while/1 (one argument) and while/2 (two arguments). The second one have two function bodies; which one to use is decided through pattern matching.

Ocaml: Equivalence of two lists

New to Ocaml and have been working on a problem I haven't seen answered yet.
I'm working on a function where there is a tuple of 2 lists that are checked for equivalence.
Example:
# equivalence ([1;2],[1;2]);;
- : bool = true
# equivalence ([1;2],[2;1]);;
- : bool = true
# equivalence ([1;2],[1]);;
- : bool = false
Code I have:
let rec equivalent(a,b) = match a, b with
| [], [] -> true
| [], _
| _, [] -> false
| c::cc, d::dd -> if c = d then equivalent(cc,dd) else false;;
I know the problem lies with the last line. I can get a result of true if all elements are in the same order, but out of order it is a result of false. I'm having trouble going through one list to see if the other list has the element. I've tried to use List.nth, .hd, and .tl (not allowed to use .map or .itr) and have also tried to avoid the imperative features of Ocaml. Any suggestions or somewhere I should look? Thanks.
I assume this is some homework where you have to treat lists as poor mans set.
As Bergi mentioned performance wise the best would be to first sort both list and then compare them with your existing code. But that is probably not how you are supposed to solve this.
Assuming the lists are mend to be sets with not duplicate entries then equivalence of a and b means that a contains every element of b and b contains every element of a.
Start by writing a function contains: 'a -> 'a list -> bool that checks if an item is in a list. Next a function contains_all: 'a list -> 'a list -> bool that uses contains to check if every item in the first list is in the second. That then gives you
let equivalence a b = (contains_all a b) && (contains_all b a)
If your lists can contains duplicates then go with sorting the lists first. Anything else is just too impractical.
Note: contains exists as List.mem if you are allowed to use that.

Why isn't this F# code tail-recursive?

I'm looking at the code in the F# 'Tutorial' template that is provided with Visual Studio 2015 and I see this code; I'm wondering why the first function isn't tail-recursive; I think I understand it but want to confirm:
/// Computes the sum of a list of integers using recursion.
let rec sumList xs =
match xs with
| [] -> 0
| y::ys -> y + sumList ys
/// Make the function tail recursive, using a helper function with a result accumulator
let rec private sumListTailRecHelper accumulator xs =
match xs with
| [] -> accumulator
| y::ys -> sumListTailRecHelper (accumulator+y) ys
Is the first one not tail recursive in the because '+' is a function and its' two arguments are evaluated first? Therefore the actual order of evaluation would be: y, then sumList ys, then +? Whereas in the second case, the order of evaluation is: accumulator,y,+ then sumListTailRecHelper(..)?
A call is tail-recursive if there's nothing left to do after the recursive call returns. So the last call amounts to going back to the start of the function code, with modified parameters.
In the first function you still have to add y to the result.

Resources