1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Data Structures With Self-Referential Types as a reasonml til

This commit is contained in:
jbranchaud
2018-07-08 15:40:39 -05:00
parent 80ac8d3cea
commit 4f06c32641
2 changed files with 31 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_686 TILs and counting..._
_687 TILs and counting..._
---
@@ -503,6 +503,7 @@ _686 TILs and counting..._
- [Break Out Of A While Loop](reason/break-out-of-a-while-loop.md)
- [Create A Stream From An Array](reason/create-a-stream-from-an-array.md)
- [Data Structures With Self-Referential Types](reason/data-structures-with-self-referential-types.md)
- [Defining Variants With Constructor Arguments](reason/defining-variants-with-constructor-arguments.md)
- [Dynamically Create A Printf String Format](reason/dynamically-create-a-printf-string-format.md)
- [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md)

View File

@@ -0,0 +1,29 @@
# Data Structures With Self-Referential Types
[ReasonML](https://reasonml.github.io/) has a powerful type system that
allows us to create types that represent all sorts of things. For data
structures like [linked lists](https://en.wikipedia.org/wiki/Linked_list),
we need a sort of recursive type, a type that can reference itself -- a
self-referential type.
Reason's type system allows us to define types that reference themselves.
Combine that with type arguments and variants -- we can create a type
definition to represents something like a linked list.
```reason
type linked_list('a) =
| Empty
| Node('a, linked_list('a));
```
A linked list is a chain of nodes. It can be an _empty_ list, hence the
first part of the variant. Otherwise, it is a node that has some data and
then points to another linked list (chain of nodes).
The `'a` part is a type argument. When creating a linked list, we can decide
what type the `'a` will be. Here is an `int`-based linked list:
```reason
let my_list: linked_list(int) = Node(25, Node(27, Empty));
/* my_list = [25] => [27] => [] */
```