Related
New to F#
I am trying to flip the sub trees on the branches.
we must use the following data types
type btree = Empty | Node of btree * int * btree
type finding = NotFound | Found of int
example tree
let s = Node (Node(Empty, 5, Node(Empty, 2, Empty)), 3, Node (Empty, 6, Empty))
(*
(3)
/ \
(5) (6)
/ \ | \
() (2) () ()
/ \
() ()
*)
here is my code so far:
let rec mirror t = function
| Node(Empty, t, Empty) -> t
| Node (t1, t, t2) ->
| _ -> failwith "Empty"
example input and output:
mirror (Node (Node (Empty, 1, Empty), 3, Node (Empty, 4, Node (Empty, 7, Empty)))
would return
Node (Node (Node (Empty, 7, Empty), 4, Empty), 3, Node (Empty, 1, Empty))
Right now the code doesn't accomplish anything, I am needing help on how I would move a nodes around to get the mirrored tree that I want.
I wonder if I must implement another function for deleting/inserting nodes? Any help is greatly appreciated!
This seems like homework, so I'll add a few learning points, before I 'hand over' the solution. Let's have a look at the code you have written already, which is not a terrible start. I have pasted it below for reference.
let rec mirror t = function
| Node(Empty, t, Empty) -> t
| Node (t1, t, t2) ->
| _ -> failwith "Empty"
You start off with allowing your function to call itself recursively, by adding the rec keyword. You are right to do that, and it's actually a pretty important realisation, that the way to go about this task, is to create a recursive function. Because, really, what does it mean to 'mirror' a tree? Mirroring means, at each node, flip the order of the subtrees, and mirror each subtree.
This is a recursive definition, since to mirror a node, you need to mirror the subtrees. So you're right about adding the rec keyword. However, in your code, you don't properly handle the terminal state Empty. Using your btree definition, you will eventually see an Empty tree, which means you will eventually throw an exception (using the failwith). This is obviously not the desired behaviour. What does the mirror of an empty tree look like? Empty! The way to handle this case, is then to replace | _ -> failwith "Empty" with | Empty -> Empty.
Now, in F#, let foo = function | ... is just syntactic sugar for let foo <arg> = match <arg> with | ..., which means your function actually takes two parameters: t and one which is hidden by the function sugar. I suppose this is not what you want, so you should either remove the currently unused parameter t, or replace function with match t with.
The reason the parameter t is currently unused, is that t is rebound to the integer node-value in the match-cases | Node(..., t, ...). This also means that the compilers current best guess, is probably that the return type of mirror should be int, rather than btree, since you return an int in the first case.
One last point is that there is no reason for handling the case with empty subtrees directly, since these are also just btrees.
Keeping all of the above in mind, I hope it makes sense why my solution to the problem is
let rec mirror = function
| Empty -> Empty
| Node(t1, i, t2) -> Node(mirror t2, i, mirror t1)
Mirroring means making the left branch the right branch and the right branch the left branch. So in your recursive function do that. For example if you start with a basic 3 node tree:
1
2 3
then mirroring that will be
1
3 2
So in code that means:
let rec mirror t = function
| Node(Empty, t, Empty) -> t
| Node (left, value, right) -> Node (right, value, left)
Except that won't work for larger trees, but it's a start. What you really want is the mirror of the right and left nodes as well. You should be able to complete the function above by adding 2 calls to mirror in the correct place in the last line of the match clause.
I am trying to create a method that takes an associative and commutative operator, as well a list of values, and then returns the answer by applying an operator to the values in the list.
The following two examples represent what the input/output are supposed to look like.
Example 1
Input: sum(fun(A,B) -> A+B end, [2,6,7,10,12]).
Output: 37
Example 2
Input: sum(fun (A,B) -> A++B end , ["C", "D", "E"]).
Output: "CDE"
This is the code I am working with so far.
-module(tester).
-compile(export_all).
sum(Func, Data, Acc) ->
lists:foldr(Func, Acc, Data).
This code produces the correct result, however, there are two problems I am trying to figure out how to approach answering.
(1) In order for this code to work, it requires an empty list to be included at the end of the command line statements. In other words, if I enter the input above (as in the examples), it will err out, because I did not write it in the following way:
12> tester:sum(fun(X, Acc) -> X+Acc end, [2,6,7,10,12], 0).
How would I implement this without an empty list as in the examples above and get the same result?
(2) Also, how would the code be implemented without the list function, or in an even more serial way?
How would I implement this without an empty list as in the examples above and get the same result?
Assuming the list always has one element (you can't really do it without this assumption), you can extract the first element from the list and pass that as the initial accumulator. You'll need to switch to foldl to do this efficiently. (With foldr you'll essentially need to make a copy of the list to drop the last element.)
sum(Func, [X | Xs]) ->
lists:foldl(fun (A, B) -> Func(B, A) end, X, Xs).
1> a:sum(fun(A,B) -> A+B end, [2,6,7,10,12]).
37
2> a:sum(fun (A,B) -> A++B end , ["C", "D", "E"]).
"CDE"
Also, how would the code be implemented without the list function, or in an even more serial way?
Here's a simple implementation using recursion and pattern matching:
sum2(Func, [X | Xs]) ->
sum2(Func, Xs, X).
sum2(Func, [], Acc) ->
Acc;
sum2(Func, [X | Xs], Acc) ->
sum2(Func, Xs, Func(Acc, X)).
We define two versions of the function. The first one extracts the head and uses that as the initial accumulator. The second one, with arity 3, does essentially what the fold functions in lists do.
After working on this for a while, this was my solution. I've left some comments about the general idea of what I did, but there's a lot more to be said.
-module(erlang2).
-compile(export_all).
-export([reduce/2]).
reduce(Func, List) ->
reduce(root, Func, List).
%When done send results to Parent
reduce(Parent, _, [A]) ->
%send to parent
Parent ! { self(), A};
%I tried this at first to take care of one el in list, but it didn't work
%length ([]) ->
% Parent ! {self(), A};
%get contents of list, apply function and store in Parent
reduce(Parent, Func, List) ->
{ Left, Right } = lists:split(trunc(length(List)/2), List),
Me = self(),
%io:format("Splitting in two~n"),
Pl = spawn(fun() -> reduce(Me, Func, Left) end),
Pr = spawn(fun() -> reduce(Me, Func, Right) end),
%merge results in parent and call Func on final left and right halves
combine(Parent, Func,[Pl, Pr]).
%merge pl and pl and combine in parent
combine(Parent, Func, [Pl, Pr]) ->
%wait for processes to complete (using receive) and then send to Parent
receive
{ Pl, Sorted } -> combine(Parent, Func, Pr, Sorted);
{ Pr, Sorted } -> combine(Parent, Func, Pl, Sorted)
end.
combine(Parent, Func, P, List) ->
%wait and store in results and then call ! to send
receive
{ P, Sorted } ->
Results = Func(Sorted, List),
case Parent of
root ->
Results;
%send results to parent
_ -> Parent ! {self(), Results}
end
end.
I want to create a function that removes any occurrence of a integer n and returns the list. I know how I want to do it but do not know the command to delete it.
Here is the data type
type alist =
A
| L of int * Alist
Here's how the data type looks:
let l = L(2, L(1, L(2, L(7, L(3, L(2, A))))))
remove 2 l;;
should return
l = L(1, L(7, L(3, A)))
Here is what I have so far:
let rec remove n l =
match (n, l) with
| (n, A) -> l
| (n, L(head,tail)) when (n = head) ->
I don't know how the how to get rid of a list or element.
You shouldn't be thinking in terms of "deleting" the list; you should instead think in terms of building a new list, without the element you want removed. I'll show you how to do that in a minute, but first I want to make a suggestion. In your match expression, you are re-using the name n in your patterns. That's a classic beginner's mistake, because it ends up confusing you. Once you know F# pretty well, that's a valid technique, but since you appear to be a beginner, I strongly suggest not doing that. Instead, use a name in your patterns that is different from the name of the thing you're matching against, because that will help teach you something. Let's rewrite your match expression with x as the name of the int in your patterns:
let rec remove n l =
match (n, l) with
| (x, A) -> l
| (x, L(head,tail)) when (x = head) ->
What each of these two patterns is doing is assigning the name x to represent the value of n if the rest of the pattern matches. Now we can more clearly see that the first pattern doesn't use the value of x at all, so it would be better to represent it by _ in that case (_ is the "wildcard" pattern, which means "I don't care about the value in this position). Thus, your match expression would become:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> // ... Still need to write this
Now let's think about what we want to do in that second match case. Here we have a node that is precisely the kind of node we want to remove from the list. So how do we go about building a list without that node in it? Well, as it happens, we already have such a list... and we've assigned it the name tail in that second match case. So at first, it might look like we could just do this:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> tail
This will return a list with the "head" node chopped off. But wait! What if the tail itself contained one or more nodes with the value we want removed? What we'd really like to return from this match case is tail, passed through a function that would remove all the nodes that match a certain value. But... wait a minute... aren't we writing a function like that right now? What if we could just call remove on the tail and have it do the rest of the work for us; wouldn't that be nice?
Well, it turns out that we can! All you have to do to remove the rest of the unwanted values from the tail list is to call remove on it! Like so:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> remove n tail
But we're not quite done yet, because there's one more possibility in your match statement. If you are using a good F# development environment (I recommend Visual Studio Code with the Ionide plugin), you should see a green wavy underline under the match keyword, and if you hover over it you should see a warning about an incomplete match expression. That's because there's one case we haven't accounted for: the case where l is a node that isn't A, but whose head value isn't equal to n. In other words, this match case:
| (x, L(head,tail)) when (x <> head) -> // What do we do here?
Well, for starters, let's simplify this match case a bit. If we put it into the complete match expression, we should see that the when guard is actually unnecessary. Match cases are checked from top to bottom, in order. Which means that if we get to the third match case, we already know that x must not be equal to head; otherwise the second match case would have been chosen! You may not be able to see why just yet, so let's put that match case into our match expression and take a look at it:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> remove n tail
| (x, L(head,tail)) when (x <> head) -> // What do we do here?
Now it's more obvious that this exactly like the previous match case, but with the opposite when guard. Which means that if we ever reach the third match case, the when expression must be true -- because if it was false, then that means that x is equal to head and so we would have gone down the second match case, not the third.
Therefore, we can actually remove the when guard from the third match case, which will now look like this:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> remove n tail
| (x, L(head,tail)) -> // What do we do here?
There's more simplification that can be done here, but it's time to look at what result we want to return. Here, we do NOT want to skip the first node of the list, but we'd still like to remove n from the tail. In fact, what we want as a result of this function is a list node containing the same head as our current list node, but with a tail that has had n removed from it. (If you don't understand that last sentence, take a minute and try to picture this in your head.) So how do we do this? Well, the simplest way is as follows:
let newTail = remove n tail
L(head, newTail)
Which can be simplified to:
L(head, remove n tail)
So the match function looks like this now:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> remove n tail
| (x, L(head,tail)) -> L(head, remove n tail)
Believe it or not, we're done! Well, almost: we have a working function now, but it's actually more complicated than it needs to be. Antoine de Saint-Exupéry is most well-known for writing The Little Prince, but he was also an aviator, who has a famous quote about design:
Il semble que la perfection soit atteinte non quand il n'y a plus rien à ajouter, mais quand il n'y a plus rien à retrancher.
In English, that's:
It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove.
So what can we remove from this function to pare it down to the absolute essentials? Well, let's start by looking at that last match case again:
| (x, L(head,tail)) -> L(head, remove n tail)
It looks like we don't use the value of x anywhere in this match case, so we don't actually need to assign a name to the int in this match case. We can just use the wildcard _ here. Once we do, our function looks like:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (x, L(head,tail)) when (x = head) -> remove n tail
| (_, L(head,tail)) -> L(head, remove n tail)
And at this point, you might think that we're really done, because we do use the value of x in the second match case, so we can't get rid of it. Or... can we? Let's look at the second match case more closely:
| (x, L(head,tail)) when (x = head) -> remove n tail
Now. The value of x here is the same as the value of n, because this match case is actually assigning the value of n to the name x by virtue of x being in the first tuple position. Right? So in the when guard, we could actually swap out x for n in the x = head check. This is legal: the checks that you do in a match case do NOT have to include only names that have appeared in the match pattern. They can be any names that your function has access to. So it's perfectly valid to swap x out for n and get the match case to look like this:
| (x, L(head,tail)) when (n = head) -> remove n tail
And now we see that we're not using the value of x in this match case either, just like in the third match case. So let's get rid of it:
| (_, L(head,tail)) when (n = head) -> remove n tail
Now let's put this match case back into our function and take a look at the function as a whole:
let rec remove n l =
match (n, l) with
| (_, A) -> l
| (_, L(head,tail)) when (n = head) -> remove n tail
| (_, L(head,tail)) -> L(head, remove n tail)
Huh. Would you look at that? The first tuple item has "I don't care" in every single spot in the match case. And yet, the function still compiles without warning about incomplete match patterns, and still runs and produces the correct values. (Try it!) So what does this tell us? It tells us that we don't actually need to have n in the value we're matching against, because we never need it in the match patterns. We need it in the when guards, but not in the match patterns themselves! So if we actually remove n from the value we're matching against, and from the match patterns, here's the result:
let rec remove n l =
match l with
| A -> l
| L(head,tail) when (n = head) -> remove n tail
| L(head,tail) -> L(head, remove n tail)
Try it. You'll see that this function also compiles, and still does exactly what you want it to do.
At this point, we really are done. Taking away anything else from this function would break it: either it wouldn't compile, or else it wouldn't return the right value. This may not be immediately obvious to you, but as your skill with F# grows, you'll learn to get a feel for when a function has been pared down to its bare essentials, and this one has.
And so there you go: after a lot of tweaking, we've gotten the remove function not just working, but working elegantly. This is the simplest you can possibly make this function, and there's a certain beauty in that. If you can see and appreciate that beauty, the beauty of a function that does exactly what it should and no more, you'll be well on your way to becoming a skilled F# programmer!
P.S. There is actually one more rewrite that we could do on this function, because it actually could be better. As it stands, this function is not always tail-recursive, which means that if you called it on a really large list, you could get a StackOverflowException. But if you haven't reached the point of studying tail recursion yet, then trying to explain how to fix this problem would be like to confuse you rather than help you understand things better. So I've deliberately chosen to end with this pared-down, elegant version of the function, rather than the version that does tail recursion "properly". Because making that improvement would produce a function that was actually more complicated and harder to understand. Once you're more experienced with F#, it'll be worth revisiting this question and asking "How do I make this function tail-recursive?". But for now, the non-tail-recursive version that we have here is the one that you should study. Once you understand how to write this function on your own, and can write other list-manipulation functions on your user-defined list data structure, then you'll have the knowledge needed to make that last improvement.
I hope this helps. Please leave a comment asking me about anything you don't understand in my explanation.
So I have some grammar that doesn't work for a top-down parser due to it having left recursion:
L::= A a | B b
A::= L b | a a
B::= b B b | b a
So in order to fix this, I have to remove the left recursion. To do this, I do a little substitute-like-thing:
L::= A a | B b
A::= A a b | B b b | a a (I plugged in the possible values of "L")
A then turns to (I believe):
A::= a a A' | B b b
A'::= a b A' | ε
I'm fairly certain that I'm correct up to there (wouldn't be surprised if I'm not, though). Where I'm struggling is now removing the left recursion out of "B b b". I've tried going about this so many ways, and I don't think any of them work. Here's one that seems most logical, but ugly as well (thus saying it's probably wrong). Starting by manipulating B::= b B b | b a
B::= b B b | b a
B::= b B' (they both start with b, so maybe i can pull it out?)
B'::= B b | a
B'::= b B' b | a (substituted B's value in)
B'::= b B" | a
B"::= b B" |a B" | ε
So I guess to show what the finalized B's would be:
B::= b B'
B'::= b B" | a
B"::= b B" | a B" | ε
This seems way too ugly to be correct. Especially since I'd have to plug that into the new "A" terminals that I created.
Can someone help me out? No idea if I'm going about this the right way. I'm supposed to be able to create an LL(1) parse table afterward (should be able to do that part on my own).
Thanks.
In a parser that tries to expand nonterminals from the left, if some nonterminal can expand to a string with itself on the left, the parser may expand that nonterminal forever without actually parsing anything. This is left recursion. On the other hand, it is perfectly fine if a nonterminal expands to a string with some different nonterminal on the left, as long as no chain of expansions produces a string with the original nonterminal on the left. Similarly, it is fine if nonterminals aren't all the way to the right in the expansion, as long as they're not all the way to the left.
tl;dr There's nothing wrong with B b b or b B b. You've removed all the left recursion. You don't need to keep going.
I have a directed cyclic graph with values at edges but no values at nodes.
The graph has a start node and an end node, and I want to preserve the set of paths through the graph but I don't care about the nodes on the path, only the edge values. Example below.
Are there any algorithms that will produce a smaller graph that preserves that property?
The graph might have 10's of thousands of nodes, but not millions. The number of edges per node is small w.r.t. the number of nodes.
Conservative heuristics are welcome.
As an example, where O is a node, and a number is the value of the adjacent edge:
O --------> O -------> O
2 3
^ |4
|1 v
1 2 3 4
start -> O -> O -> O -> end
|5 ^
v |8
O --------> O -------> O
6 7
has two paths with edge values [1,2,3,4] from start to end, so one is redundant, and I would be happy to reduce the above to
O --------> O -------> O
2 3
^ |4
|1 v
start end
|5 ^
v |8
O --------> O -------> O
6 7
The graph can be cyclic, so in
1
/-\
| /
v/
start -> O -> O -> end
1 1 2
a simpler graph would eliminate the second 1 transition to leave only the self-edge:
1
/-\
| /
v/
start -> O -> end
1 2
I would iterate through all nodes that are not the start and end and proceed to remove them. When removing a node you add another edge between all nodes that were connected through this node (watch direction since its a directed graph). The thing to remember is that if you try to add an edge that already exists due to this process - make sure to keep the edge with the smaller weight (that's the key).
Implication Charts did what I need. They're O(n**2) space-wise on the number of nodes, but that's manageable in my situation.