Skip to content

Instantly share code, notes, and snippets.

@zdimension
Last active November 12, 2021 15:20
Show Gist options
  • Save zdimension/e34e0ae3f57f328b55fb6a55bedd2b36 to your computer and use it in GitHub Desktop.
Save zdimension/e34e0ae3f57f328b55fb6a55bedd2b36 to your computer and use it in GitHub Desktop.
from dataclasses import dataclass
from typing import Any
@dataclass
class List:
pass
@dataclass
class Empty(List):
def __iter__(self):
return
yield
@dataclass
class Cons(List):
head: Any
tail: List
def __iter__(self):
yield self.head
yield from self.tail
def newList():
return Empty()
def isEmpty(l):
match l:
case Empty():
return True
case Cons():
return False
def car(l):
match l:
case Cons(head, tail):
return head
case Empty():
raise Error("car of empty list")
def cdr(l):
match l:
case Cons(head, tail):
return tail
case Empty():
raise Error("cdr of empty list")
def showList(l):
match l:
case Cons(head, tail):
return f"{head} -> {showList(tail)}"
case Empty():
return "ø"
l = newList()
l1 = Cons(15,Cons(12,Cons(2,l)))
v = car(l1)
l2 = cdr(l1)
l3 = Cons(4,Cons(5, l2))
print(showList(l))
print(showList(l1))
print(v)
print(showList(l2))
print(showList(l3))
from dataclasses import dataclass
from typing import Any
@dataclass
class List:
pass
@dataclass
class Empty(List):
def __iter__(self):
return
yield
def isEmpty(self):
return True
def car(self):
raise Error("car of empty list")
def cdr(self):
raise Error("cdr of empty list")
def show(self):
return "ø"
@dataclass
class Cons(List):
head: Any
tail: List
def __iter__(self):
yield self.head
yield from self.tail
def isEmpty(self):
return False
def car(self):
return self.head
def cdr(self):
return self.tail
def show(self):
return f"{self.head} -> {self.tail.show()}"
def newList():
return Empty()
l = newList()
l1 = Cons(15,Cons(12,Cons(2,l)))
v = l1.car()
l2 = l1.cdr()
l3 = Cons(4,Cons(5, l2))
print(l.show())
print(l1.show())
print(v)
print(l2.show())
print(l3.show())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment