stefan.kruger
2019-11-4 16:24:27

I implemented a simple tree structure — a node has a set of child-nodes type of thing — and an insert function that traverses breadth first to find the parent node under which to add a child node:


stefan.kruger
2019-11-4 16:24:44

stefan.kruger
2019-11-4 16:25:20

It seems to do what I wanted it to do. However, could I have achieved the same thing in a non-mutable way?


badkins
2019-11-4 16:33:10

badkins
2019-11-4 16:34:23

Short answer is, “yes”, you can insert into a tree in a functional way w/o mutation.


stefan.kruger
2019-11-4 16:38:03

Related question — is it considered dirty to reach for mutability in Racket? I just worry my Racket looks like Python :slightly_smiling_face:


badkins
2019-11-4 16:43:17

I’m sure opinions will vary widely, but I do try to go for a functional approach first as a matter of habit. When I use mutation, which is rarely, I try and localize it as much as possible. It’s nice that Racket allows mutation when needed though :slightly_smiling_face:


badkins
2019-11-4 16:44:12

As an example of “localize”, I will occasionally use set! inside a single function where I’m only mutating a variable local to that function.


soegaard2
2019-11-4 16:58:42

@stefan.kruger FWIW here is the code for a functional red black tree done in Racket: http://planet.racket-lang.org/package-source/soegaard/galore.plt/4/2/private/red-black-tree.ss


soegaard2
2019-11-4 17:00:00

The B struct is a tree with a black top node and the R struct is a tree with a red top node.


soegaard2
2019-11-4 17:00:56

The old match used $ to match structs, so ($ B l x r) matches a tree where the node element x is black and the l and r is the left and right sub trees respectively.


soegaard2
2019-11-4 17:02:09

The book by Okasaki is top-notch. The basis of the book was his thesis: https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf


stefan.kruger
2019-11-4 17:02:52

Sounds like $40 of worthwhile spend.


soegaard2
2019-11-4 17:03:22

I admit I got obsessed with implementing data structures after reading it.


stefan.kruger
2019-11-4 17:05:58

Bought.