Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from collections import namedtuple
  4.  
  5. Nil = namedtuple('Nil', ())
  6. Cons = namedtuple('Cons', ('car', 'cdr'))
  7.  
  8.  
  9. def null(lst):
  10.     return Nil() == lst
  11.  
  12.  
  13. def fromseq(seq):
  14.     if not seq:
  15.         return Nil()
  16.     return Cons(seq[0], fromseq(seq[1:]))
  17.  
  18.  
  19. def head(lst):
  20.     if null(lst):
  21.         raise AttributeError()
  22.     h, _ = lst
  23.     return h
  24.  
  25.  
  26. def tail(lst):
  27.     if null(lst):
  28.         raise AttributeError()
  29.     _, t = lst
  30.     return t
  31.  
  32.  
  33. def foldr(func, acc, lst):
  34.     if null(lst):
  35.         return acc
  36.     return foldr(func, func(head(lst), acc), tail(lst))
  37.  
  38.  
  39. def foldl(func, acc, lst):
  40.     if null(lst):
  41.         return acc
  42.     return foldl(func, func(acc, head(lst)), tail(lst))
  43.  
  44.  
  45. def length(lst):
  46.     if null(lst):
  47.         return 0
  48.     return 1 + length(tail(lst))
  49.  
  50.  
  51. def tolist(lst):
  52.     if null(lst):
  53.         return []
  54.  
  55.     return [head(lst)] + tolist(tail(lst))
  56.  
  57.  
  58. def map_(func, lst):
  59.     if null(lst):
  60.         return Nil()
  61.     return Cons(func(head(lst)), map_(func, tail(lst)))
  62.  
  63.  
  64. def append(lst1, lst2):
  65.     if null(lst1):
  66.         return lst2
  67.     return Cons(head(lst1), append(tail(lst1), lst2))
  68.  
  69.  
  70. def filter_(pred, lst):
  71.     if null(lst):
  72.         return Nil()
  73.  
  74.     if pred(head(lst)):
  75.         return Cons(head(lst), filter_(pred, tail(lst)))
  76.     else:
  77.         return filter_(pred, tail(lst))
  78.  
  79.  
  80. def reverse(lst):
  81.     if null(lst):
  82.         return Nil()
  83.     return append(reverse(tail(lst)), Cons(head(lst), Nil()))
  84.  
  85.  
  86. def elem(value, lst):
  87.     if null(lst):
  88.         return False
  89.     if head(lst) == value:
  90.         return True
  91.     return elem(value, tail(lst))
  92.  
  93.  
  94. if __name__ == '__main__':
  95.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement