Let's say I have a binary tree data structure defined as follows
type 'a tree =
| Node of 'a tree * 'a * 'a tree
| Nil
I have an instance of a tree as follows:
let x =
Node
(Node (Node (Nil,35,Node (Nil,40,Nil)),48,Node (Nil,52,Node (Nil,53,Nil))),
80,Node (Node (Nil,82,Node (Nil,83,Nil)),92,Node (Nil,98,Nil)))
I'm trying to pretty-print the tree into something easy to interpret. Preferably, I'd like to print the tree in a console window like this:
_______ 80 _______
/ \
_ 48 _ _ 92 _
/ \ / \
35 52 82 98
\ \ /
40 53 83
What's an easy way to get my tree to output in that format?
If you want it to be very pretty, you could steal about 25 lines of code from this blog entry to draw it with WPF.
But I'll code up an ascii solution shortly too, probably.
EDIT
Ok, wow, that was hard.
I'm not certain it's entirely correct, and I can't help but think there's probably a better abstraction. But anyway... enjoy!
(See the end of the code for a large example that is rather pretty.)
type 'a tree =
| Node of 'a tree * 'a * 'a tree
| Nil
(*
For any given tree
ddd
/ \
lll rrr
we think about it as these three sections, left|middle|right (L|M|R):
d | d | d
/ | | \
lll | | rrr
M is always exactly one character.
L will be as wide as either (d's width / 2) or L's width, whichever is more (and always at least one)
R will be as wide as either ((d's width - 1) / 2) or R's width, whichever is more (and always at least one)
(above two lines mean 'dddd' of even length is slightly off-center left)
We want the '/' to appear directly above the rightmost character of the direct left child.
We want the '\' to appear directly above the leftmost character of the direct right child.
If the width of 'ddd' is not long enough to reach within 1 character of the slashes, we widen 'ddd' with
underscore characters on that side until it is wide enough.
*)
// PrettyAndWidthInfo : 'a tree -> string[] * int * int * int
// strings are all the same width (space padded if needed)
// first int is that total width
// second int is the column the root node starts in
// third int is the column the root node ends in
// (assumes d.ToString() never returns empty string)
let rec PrettyAndWidthInfo t =
match t with
| Nil ->
[], 0, 0, 0
| Node(Nil,d,Nil) ->
let s = d.ToString()
[s], s.Length, 0, s.Length-1
| Node(l,d,r) ->
// compute info for string of this node's data
let s = d.ToString()
let sw = s.Length
let swl = sw/2
let swr = (sw-1)/2
assert(swl+1+swr = sw)
// recurse
let lp,lw,_,lc = PrettyAndWidthInfo l
let rp,rw,rc,_ = PrettyAndWidthInfo r
// account for absent subtrees
let lw,lb = if lw=0 then 1," " else lw,"/"
let rw,rb = if rw=0 then 1," " else rw,"\\"
// compute full width of this tree
let totalLeftWidth = (max (max lw swl) 1)
let totalRightWidth = (max (max rw swr) 1)
let w = totalLeftWidth + 1 + totalRightWidth
(*
A suggestive example:
dddd | d | dddd__
/ | | \
lll | | rr
| | ...
| | rrrrrrrrrrr
---- ---- swl, swr (left/right string width (of this node) before any padding)
--- ----------- lw, rw (left/right width (of subtree) before any padding)
---- totalLeftWidth
----------- totalRightWidth
---- - ----------- w (total width)
*)
// get right column info that accounts for left side
let rc2 = totalLeftWidth + 1 + rc
// make left and right tree same height
let lp = if lp.Length < rp.Length then lp # List.init (rp.Length-lp.Length) (fun _ -> "") else lp
let rp = if rp.Length < lp.Length then rp # List.init (lp.Length-rp.Length) (fun _ -> "") else rp
// widen left and right trees if necessary (in case parent node is wider, and also to fix the 'added height')
let lp = lp |> List.map (fun s -> if s.Length < totalLeftWidth then (nSpaces (totalLeftWidth - s.Length)) + s else s)
let rp = rp |> List.map (fun s -> if s.Length < totalRightWidth then s + (nSpaces (totalRightWidth - s.Length)) else s)
// first part of line1
let line1 =
if swl < lw - lc - 1 then
(nSpaces (lc + 1)) + (nBars (lw - lc - swl)) + s
else
(nSpaces (totalLeftWidth - swl)) + s
// line1 right bars
let line1 =
if rc2 > line1.Length then
line1 + (nBars (rc2 - line1.Length))
else
line1
// line1 right padding
let line1 = line1 + (nSpaces (w - line1.Length))
// first part of line2
let line2 = (nSpaces (totalLeftWidth - lw + lc)) + lb
// pad rest of left half
let line2 = line2 + (nSpaces (totalLeftWidth - line2.Length))
// add right content
let line2 = line2 + " " + (nSpaces rc) + rb
// add right padding
let line2 = line2 + (nSpaces (w - line2.Length))
let resultLines = line1 :: line2 :: ((lp,rp) ||> List.map2 (fun l r -> l + " " + r))
for x in resultLines do
assert(x.Length = w)
resultLines, w, lw-swl, totalLeftWidth+1+swr
and nSpaces n =
String.replicate n " "
and nBars n =
String.replicate n "_"
let PrettyPrint t =
let sl,_,_,_ = PrettyAndWidthInfo t
for s in sl do
printfn "%s" s
let y = Node(Node (Node (Nil,35,Node (Node(Nil,1,Nil),88888888,Nil)),48,Node (Nil,777777777,Node (Nil,53,Nil))),
80,Node (Node (Nil,82,Node (Nil,83,Nil)),1111111111,Node (Nil,98,Nil)))
let z = Node(y,55555,y)
let x = Node(z,4444,y)
PrettyPrint x
(*
___________________________4444_________________
/ \
________55555________________ ________80
/ \ / \
________80 ________80 _______48 1111111111
/ \ / \ / \ / \
_______48 1111111111 _______48 1111111111 35 777777777 82 98
/ \ / \ / \ / \ \ \ \
35 777777777 82 98 35 777777777 82 98 88888888 53 83
\ \ \ \ \ \ /
88888888 53 83 88888888 53 83 1
/ /
1 1
*)
If you don't mind turning your head sideways, you can print the tree depth first, one node to a line, recursively passing the depth down the tree, and printing depth*N spaces on the line before the node.
Here's Lua code:
tree={{{nil,35,{nil,40,nil}},48,{nil,52,{nil,53,nil}}},
80,{{nil,82,{nil,83,nil}},92 {nil,98,nil}}}
function pptree (t,depth)
if t ~= nil
then pptree(t[3], depth+1)
print(string.format("%s%d",string.rep(" ",depth), t[2]))
pptree(t[1], depth+1)
end
end
Test:
> pptree(tree,4)
98
92
83
82
80
53
52
48
40
35
>
Maybe this can help: Drawing Trees in ML
Although it's not exactly the right output, I found an answer at http://www.christiankissig.de/cms/files/ocaml99/problem67.ml :
(* A string representation of binary trees
Somebody represents binary trees as strings of the following type (see example opposite):
a(b(d,e),c(,f(g,)))
a) Write a Prolog predicate which generates this string representation, if the tree
is given as usual (as nil or t(X,L,R) term). Then write a predicate which does this
inverse; i.e. given the string representation, construct the tree in the usual form.
Finally, combine the two predicates in a single predicate tree_string/2 which can be
used in both directions.
b) Write the same predicate tree_string/2 using difference lists and a single
predicate tree_dlist/2 which does the conversion between a tree and a difference
list in both directions.
For simplicity, suppose the information in the nodes is a single letter and there are
no spaces in the string.
*)
type bin_tree =
Leaf of string
| Node of string * bin_tree * bin_tree
;;
let rec tree_to_string t =
match t with
Leaf s -> s
| Node (s,tl,tr) ->
String.concat ""
[s;"(";tree_to_string tl;",";tree_to_string tr;")"]
;;
This is an intuition, I'm sure someone like Knuth had the idea, I'm too lazy
to check.
If you look at your tree as an one dimensional structure you will get an array
(or vector) of length L
This is easy to build with an "in order" recursive tree traversal: left,root,right
some calculations must be done to fill the gaps when the tree is unbalanced
2 dimension
_______ 80 _______
/ \
_ 48 _ _ 92 _
/ \ / \
35 52 82 98
\ \ /
40 53 83
1 dimension :
35 40 48 52 53 80 83 82 92 98
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
The pretty printed tree can be build using this array
(maybe with something recursive)
first using values at L/2 position, the X position is the
L/2 value * the default length (here it is 2 characters)
80
then (L/2) - (L/4) and (L/2) + (L/4)
48 92
then L/2-L/4-L/8, L/2-L/4+L/8, L/2+L/4-L/8 and L/2+L/4+L/8
35 52 82 98
...
Adding pretty branches will cause more positional arithmetics but it's trivial here
You can concatenate values in a string instead using an array, concatenation will
de facto calculate the best X postion and will allow different value size,
making a more compact tree.
In this case you will have to count the words in the string to extract
the values. ex: for the first element using the L/2th word of the string instead
of the L/2 element of the array. The X position in the string is the same in the tree.
N 35 40 48 N 52 53 80 83 82 N 92 N 98 N
80
48 92
35 52 82 98
40 53 83
Related
I would like to convert a list of zeros and ones to a char.
example :
bitToChar([1,0,0,0,1,0,1]) = $Q
Thanks.
Another way to do it is to use a bit string comprehension:
X = [1,0,0,0,1,0,1],
<<C:7>> = << <<Bit:1>> || Bit <- lists:reverse(X) >>,
$Q == C.
That is, pick one element at a time from the list, and use each element as a bit in the binary being built, and finally extract a seven-bit number into the variable C.
You can add $0 to each of them (to make it a string with $0s and $1s), reverse the list, and use list_to_integer/2 with base 2:
1> list_to_integer(lists:reverse([N + $0 || N <- [1,0,0,0,1,0,1]]), 2) == $Q.
true
You can also use lists:foldl. The code is slightly longer but it doesn't use list_to_binary:
1> element(2, lists:foldl(fun(Digit, {Mul, Acc}) -> {Mul * 2, Acc + Digit * Mul} end, {1, 0}, Xs)) == $Q. true
This is basically equivalent to doing: 1 * 1 + 0 * 2 + 0 * 4 + 0 * 8 + 1 * 16 + 0 * 32 + 1 * 64.
$Q = lists:foldr(fun(X,Acc) -> X + (Acc bsl 1) end, 0,[1,0,0,0,1,0,1]).
Since $Q is integer value all you have to do is use in BitToChar conversion from binary based number to decimal based number.
Simplest conversion is:
to_decimal(X) ->
to_decimal(lists:reverse(X), 1, 0).
% you can validate that if H = 1 then add, if other not but I omitted this validation
to_decimal([H | T], Times, Acc) ->
to_decimal(T, 2 * Times, H * Times + Acc);
to_decimal([], _Times, Acc) -> Acc.
And then it will return integer.
In your case:
> $Q = 81.
81
> $Q == 81.
true
I created my own datatype And I'm trying to create the sum of all the numbers in that datatype which is a list of lists. I don't want to use any F# libraries
My datatype
type elist = A | L of int * elist
I'm a beginner in F# and trying to grasp my head on it. I want to do this recursively. My thinking going into it is to traverse to the end of the list and start an sum and go back to the front and add each one.
example:
let l = L(4, L(3, L(6, L(3, A))))
that should return
val it : int 16
Here's my code and I know it is wrong:
let rec sum l =
let a = 0
match l with
| A -> 0
| L(head,A) -> head
| L(head,tail) -> sum tail + a
You're nearly there. All you need is to lose the a:
let rec sum l =
match l with
| A -> 0
| L(head,A) -> head
| L(head,tail) -> head + sum tail
Then evaluating sum l when l = L(4, L(3, L(6, L(3, A)))) gives
val it : int = 16
as required.
Is there a concise functional way to rename columns of a Deedle data frame f?
f.RenameColumns(...) is usable, but mutates the data frame it is applied to, so it's a bit of a pain to make the renaming operation idempotent. I have something like f.RenameColumns (fun c -> ( if c.IndexOf( "_" ) < 0 then c else c.Substring( 0, c.IndexOf( "_" ) ) ) + "_renamed"), which is ugly.
What would be nice is something that creates a new frame from the input frame, like this: Frame( f |> Frame.cols |> Series.keys |> Seq.map someRenamingFunction, f |> Frame.cols |> Series.values ) but this gets tripped up by the second part -- the type of f |> Frame.cols |> Series.values is not what is required by the Frame constructor.
How can I concisely transform f |> Frame.cols |> Series.values so that its result is edible by the Frame constructor?
You can determine its function when used with RenameColumns:
df.RenameColumns someRenamingFunction
You can also use the function Frame.mapColKeys.
Builds a new data frame whose columns are the results of applying the
specified function on the columns of the input data frame. The
function is called with the column key and object series that
represents the column data.
Source
Example:
type Record = {Name:string; ID:int ; Amount:int}
let data =
[|
{Name = "Joe"; ID = 51; Amount = 50};
{Name = "Tomas"; ID = 52; Amount = 100};
{Name = "Eve"; ID = 65; Amount = 20};
|]
let df = Frame.ofRecords data
let someRenamingFunction s =
sprintf "%s(%i)" s s.Length
df.Format() |> printfn "%s"
let ndf = df |> Frame.mapColKeys someRenamingFunction
ndf.Format() |> printfn "%s"
df.RenameColumns someRenamingFunction
df.Format() |> printfn "%s"
Print:
Name ID Amount
0 -> Joe 51 50
1 -> Tomas 52 100
2 -> Eve 65 20
Name(4) ID(2) Amount(6)
0 -> Joe 51 50
1 -> Tomas 52 100
2 -> Eve 65 20
Name(4) ID(2) Amount(6)
0 -> Joe 51 50
1 -> Tomas 52 100
2 -> Eve 65 20
say I have a Frame, which looks like below,
" Name ID Amount
0 -> Joe 51 50
1 -> Tomas 52 100
2 -> Eve 65 20
3 -> Suzanne 67 10
4 -> Suassss 69 10
5 -> Suzanne 70 10
6 -> Suzanne 78 1
7 -> Suzanne 79 10
8 -> Suzanne 80 12
9 -> Suzanne 85 10
10 -> Suzanne 87 10
...
What I would like to achieve is to group or aggregate base on the ID column such that if a sequence of running number is encountered, those rows should be grouped together, otherwise, the row itself is a group.
I belive a recursive function is your friend here.
Feed a list of tuples
let data = [(Joe, 51, 50);
(Tomas, 52, 100);
(Eve, 65, 20);
(Suzanne, 67, 10)]
to a function
let groupBySequencialId list =
let rec group result acc data lastId =
match data with
| [] -> acc :: result
| (name, id, amount) :: tail ->
if lastId + 1 = id then
group result ((name, id, amount) :: acc) tail id
else
group (acc :: result) ([(name, id, amount)]) tail id
group [] [] data 0
and you'll get the result you are looking for.
This should get the job done save three caveats.
You need to parse your string into the tuples required
There's an empty list in the result set because the first recursion wont match and appends the empty accumulator to the result set
The list will come out be reversed
Also note that this is a highly specialized function.
If I was you, I'd try to make this more general, if you ever plan on reusing it.
Have fun.
let rec aggregateList (f:int->int->int) init list =
match list with
| [] -> init
| hd::tl ->
let rem = aggregateList f init tl
f rem hd
let add a b = a + b
let mul a b = a * b
//to use in F# Interactive:
//aggregateList add 0 [1..5];;
Got this example from "Functional Programming for the Real world" by Thomas Petricek
I don't understand in second branch in that pattern matching: f rem hd.
Could somebody help me?
Let's break down the aggregateList function declaration first. The function takes three parameters:
A function, named f, that takes two ints and returns a third int.
The initial value to start aggregating with.
A list of values.
The function then matches the list it is supplied with one of two possibilities:
The list is empty, in which case it returns the value of init.
The list is not empty, in which case it takes the first item and assigns it to hd (or head) and the rest of the list and assigns it to tl (or tail). Then it performs the recursive call aggregateList f init tl. When that returns, it takes the result and assigns it to rem. Then it calls f on rem and hd.
As other people have pointed out, this does the same thing as the List.foldback function in the basic F# library.
Be careful, of course, to choose the init value properly because if you executed aggregateList mul 0 somelist;; you'll just get 0 no matter what list you supply.
It calls the function f (one of the parameters) giving it the result of the recursive call and the next item.
rem is the remainder, or in this case the result of the remainder of the values.
hd is the next item, as seen in the | hd::tl -> part of the pattern matching.
Effectively this aggregate function takes a function, a starting point, and a list. A way of representing the example line is:
(1 + (2 + (3 + (4 + (5 + 0)))))
Just for fun, let's do some printf style debugging:
> aggregateList (fun acc x -> printf "%i " x; acc + x) 0 [1..10];;
10 9 8 7 6 5 4 3 2 1 val it : int = 55
It looks like the function is equivalent to List.foldBack (or fold_right in other languages): it walks each item in the list from right to left and invokes a function f on them.
Let's re-write the function in a few different ways:
// functional version
let rec foldBack f seed = function
| [] -> seed
| x::xs -> let res = foldBack f seed xs in f res x
// imperative version
let foldBack f seed xs =
let mutable result = seed
for x in List.rev xs do
result <- f result x
result
// C# equivalent
public static U FoldBack<T, U>(Func<T, U> f, U seed, IEnumerable<T> xs) {
foreach(T x in xs.Reverse())
seed = f(seed, x);
return seed;
}
You'd use the function like this:
let sum = foldBack (+) 0 [1..10] // returns 55
let sumOfSquares = foldBack (fun acc x -> acc + x * x) 0 [1..10];; // 385
I don't understand in second branch in
that pattern matching: f rem hd. Could
somebody help me?
So let's start with what we already know about F# functions:
f is a function with the type int -> int -> int. You pass functions around as if they were any other variable like ints or strings.
You call functions by passing a space-separated list of arguments. f rem hd invokes the function f with two arguments, rem and hd.
The last expression evaluated in a function is treated as the function's return value.
So going back to the original function:
let rec aggregateList (f:int->int->int) init list =
match list with
| [] -> init
| hd::tl ->
let rem = aggregateList f init tl // 1
f rem hd // 2
In line 1, we call aggregateList recusively with tl. Since the list gets smaller and smaller, we're eventually going to hit the nil case, which returns init.
In line 2, f rem hd is the function's return value. However, since we recursed down the stack as we made our way to end of the list, we're going to call this function one for each element (in right-to-left order) as we walk back up the stack trace.
Given aggregateList (+) 0 [1..10], the nil case returns 0, so we call:
return value = f rem hd = f 0 10 = 0 + 10 = 10
return value = f rem hd = f 10 9 = 9 + 10 = 19
return value = f rem hd = f 19 8 = 19 + 8 = 27
return value = f rem hd = f 27 7 = 27 + 7 = 34
return value = f rem hd = f 34 6 = 34 + 6 = 40
return value = f rem hd = f 40 5 = 40 + 5 = 45
return value = f rem hd = f 45 4 = 45 + 4 = 49
return value = f rem hd = f 49 3 = 49 + 3 = 52
return value = f rem hd = f 52 2 = 52 + 2 = 54
return value = f rem hd = f 54 1 = 54 + 1 = 55
No more items in the list, so the whole function returns 55.
As you can imagine, the nested calls in aggregateList evaluate like this for a list of length n:
f (f (f (f (f (f (f (f init hdn) hdn-1) hdn-2) hdn-3) ... hd2) hd1) hd0