Is it possible to type a non-empty list? #3368
-
Hi, I've been experimenting with Gleam recently and I was wondering if it was possible to type a non-empty list in Gleam? e.g. pub fn of(items: NonEmptyList(a)) -> Node(a) {
// ...
}
of([]) // error
of(["👍"]) // ok Without being able to type a non-empty list the signature would need to be pub fn of(items: List(a)) -> Option(Node(a)) {
// ...
} but then the constructor may return |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
The following works but feels wrong let assert Some(list) = linked_list.of([1, 2]) |
Beta Was this translation helpful? Give feedback.
-
I added an pub type Node(a) {
Node(data: a, next: Node(a))
Empty
} A non-empty list was not necessary in this case. I'm not sure if it would be useful in other cases or if it is just a skill issue 😅. P.S. Yes, I'm aware the build-in list type is a singly-linked list. I'm doing this as a learning exercise. |
Beta Was this translation helpful? Give feedback.
-
Hello! There's a non-empty list in this package: https://github.com/giacomocavalieri/non_empty_list |
Beta Was this translation helpful? Give feedback.
-
One thing to keep in mind is that in Gleam the Option type is never used for success and failure, only things that are nullable. https://hexdocs.pm/gleam_stdlib/gleam/option.html#Option |
Beta Was this translation helpful? Give feedback.
I added an
Empty
state to myNode
type and that removed the need for a non-empty list. i.e.A non-empty list was not necessary in this case. I'm not sure if it would be useful in other cases or if it is just a skill issue 😅.
P.S. Yes, I'm aware the build-in list type is a singly-linked list. I'm doing this as a learning exercise.