Created
March 8, 2024 18:19
-
-
Save bkyrlach/f274d65ab628007a47f8c17e32d84261 to your computer and use it in GitHub Desktop.
Stack/LinkedList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed trait Thing[+A] | |
object Thing { | |
case class SomeThing[A](value: A, next: Thing[A]) extends Thing[A] | |
case object NotAThing extends Thing[Nothing] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I can use `Thing` as a Linked List | |
//These are the two most important... | |
def headOption[A](xs: Thing[A]): Option[A] = xs match { | |
case SomeThing(a, _) => Some(a) | |
case NotAThing => None | |
} | |
def tail[A](xs: Thing[A]): Thing[A] = xs match { | |
case SomeThing(_, rest) => rest | |
case NotAThing => NotAThing | |
} | |
// But I can also do things like... | |
def take[A](xs: Thing[A])(n: Int): Thing[A] = | |
if(n <= 0) NotAThing else xs match { | |
case SomeThing(first, rest) => SomeThing(first, take(rest)(n - 1)) | |
case NotAThing => NotAThing | |
} | |
def map[A,B](xs: Thing[A])(f: A => B): Thing[B] = xs match { | |
case SomeThing(first, rest) => SomeThing(f(first), map(rest)(f)) | |
case NotAthing => NotAThing | |
} | |
// You get the idea | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// But you can also use this like a stack | |
def peek[A](stack: Thing[A]): Option[A] = stack match { | |
case SomeThing(first, _) => Some(first) | |
case NotAThing => None | |
} | |
def push[A](stack: Thing[A])(a: A): Thing[A] = SomeThing(a, stack) | |
def pop(stack: Thing[A]): (Option[A], Thing[A]) = stack match { | |
case SomeThing(first, rest) => (Some(first), rest) | |
case NotAThing => (None, stack) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@OmarShehata You have single-handedly restored my faith in humanity. I think your analysis/understanding of my argument and what happened in that Twitter thread are spot on.
Thank you so much. I’ve been feeling so crappy watching all of these notifications come in calling me terrible things. I hope you’re having a lovely day wherever you are.