Tomohiko Himura
December 06, 2015
230

内包表記とPythonとOption

LT駆動開発21 - 闇夜深し輝け稲妻の語りの発表資料です。
https://github.com/LTDD/Sessions/wiki/LT%E9%A7%86%E5%8B%95%E9%96%8B%E7%99%BA21

Tomohiko Himura

December 06, 2015

Transcript

5. None
6. None

11. None

2 4 6 8

15. 内包と外延 • 内包: 性質をかく • [ (x, y) | x

<- [1,2], y <- ["A","B"]] • 外延: 全部かく • [(1, "A"), (1, "B"), (2, "A"), (2, "B")]
16. python [ (x,y) for x in [1, 2] for y

in ["A", "B"] ]

yield (x, y)

22. def add(x, y): if x != None: if y !=

None: return x + y add(1,2) # => 3 add(None, 2) # => None add(1, None) # => None

24. def add(x: Option[Int], y: Option[Int]): Option[Int] = for { x_

<- x y_ <- y } yield x_ + y_ add(Some(1), Some(2)) // => Some(3) add(Some(1), None) // => None add(None, Some(2) // => None

28. class Option: def __init__(self, value): self.value = value def __iter__(self):

return self def next(self): if self.value == None: raise StopIteration else: ret = self.value self.value = None return ret def __str__(self): if self.value == None: return "Nothing" else: return "Some(%d)" % self.value
29. def add(x, y): return [ x_+ y_ for x_ in

x for y_ in y ] add(Option(1), Option(2)) # => [3] add(Option(1), Option(None)) # => [] add(Option(None), Option(2)) # => []

31. class Option: def __init__(self, value): self.value = value def __iter__(self):

return self def next(self): if self.value == None: raise StopIteration else: ret = self.value self.value = None return ret def __str__(self): if self.value == None: return "Nothing" else: return "Some(%d)" % self.value