Is there a Python equivalent of the Haskell 'let'

前端 未结 9 1266
青春惊慌失措
青春惊慌失措 2020-12-29 21:38

Is there a Python equivalent of the Haskell \'let\' expression that would allow me to write something like:

list2 = [let (name,size)=lookup(productId) in (ba         


        
9条回答
  •  我在风中等你
    2020-12-29 22:03

    Although you can simply write this as:

    list2 = [(barcode(pid), metric(lookup(pid)[1]))
             for pid in list]
    

    You could define LET yourself to get:

    list2 = [LET(('size', lookup(pid)[1]),
                 lambda o: (barcode(pid), metric(o.size)))
             for pid in list]
    

    or even:

    list2 = map(lambda pid: LET(('name_size', lookup(pid),
                                 'size', lambda o: o.name_size[1]),
                                lambda o: (barcode(pid), metric(o.size))),
                list)
    

    as follows:

    import types
    
    def _obj():
      return lambda: None
    
    def LET(bindings, body, env=None):
      '''Introduce local bindings.
      ex: LET(('a', 1,
               'b', 2),
              lambda o: [o.a, o.b])
      gives: [1, 2]
    
      Bindings down the chain can depend on
      the ones above them through a lambda.
      ex: LET(('a', 1,
               'b', lambda o: o.a + 1),
              lambda o: o.b)
      gives: 2
      '''
      if len(bindings) == 0:
        return body(env)
    
      env = env or _obj()
      k, v = bindings[:2]
      if isinstance(v, types.FunctionType):
        v = v(env)
    
      setattr(env, k, v)
      return LET(bindings[2:], body, env)
    

提交回复
热议问题