Skip to content

Commit 4f06c32

Browse files
committed
Add Data Structures With Self-Referential Types as a reasonml til
1 parent 80ac8d3 commit 4f06c32

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_686 TILs and counting..._
13+
_687 TILs and counting..._
1414

1515
---
1616

@@ -503,6 +503,7 @@ _686 TILs and counting..._
503503

504504
- [Break Out Of A While Loop](reason/break-out-of-a-while-loop.md)
505505
- [Create A Stream From An Array](reason/create-a-stream-from-an-array.md)
506+
- [Data Structures With Self-Referential Types](reason/data-structures-with-self-referential-types.md)
506507
- [Defining Variants With Constructor Arguments](reason/defining-variants-with-constructor-arguments.md)
507508
- [Dynamically Create A Printf String Format](reason/dynamically-create-a-printf-string-format.md)
508509
- [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Data Structures With Self-Referential Types
2+
3+
[ReasonML](https://reasonml.github.io/) has a powerful type system that
4+
allows us to create types that represent all sorts of things. For data
5+
structures like [linked lists](https://en.wikipedia.org/wiki/Linked_list),
6+
we need a sort of recursive type, a type that can reference itself -- a
7+
self-referential type.
8+
9+
Reason's type system allows us to define types that reference themselves.
10+
Combine that with type arguments and variants -- we can create a type
11+
definition to represents something like a linked list.
12+
13+
```reason
14+
type linked_list('a) =
15+
| Empty
16+
| Node('a, linked_list('a));
17+
```
18+
19+
A linked list is a chain of nodes. It can be an _empty_ list, hence the
20+
first part of the variant. Otherwise, it is a node that has some data and
21+
then points to another linked list (chain of nodes).
22+
23+
The `'a` part is a type argument. When creating a linked list, we can decide
24+
what type the `'a` will be. Here is an `int`-based linked list:
25+
26+
```reason
27+
let my_list: linked_list(int) = Node(25, Node(27, Empty));
28+
/* my_list = [25] => [27] => [] */
29+
```

0 commit comments

Comments
 (0)