Upgrade to Pro — share decks privately, control downloads, hide ads and more …

内包表記とPythonとOption

 内包表記と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
Tweet

More Decks by Tomohiko Himura

Other Decks in Programming

Transcript

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

    <- [1,2], y <- ["A","B"]] • 外延: 全部かく • [(1, "A"), (1, "B"), (2, "A"), (2, "B")]
  2. 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
  3. 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
  4. 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
  5. 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)) # => []
  6. 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