Arc Forumnew | comments | leaders | submitlogin
Ask Arc: how will this python code translate to Arc?
4 points by adm 5625 days ago | 8 comments

  def brackify(openb, closeb):
    def func(val): return openb + val + closeb
    return func

  rbrackify = brackify('(', ')')
  cbrackify = brackify('{', '}')
  sbrackify = brackify('[', ']')

  >rbrackify("adm")
  >> "(adm)"
  >cbrackify("adm")
  >> "{adm}"


5 points by absz 5625 days ago | link

Almost line-for-line:

  (def brackify (openb closeb)
    [+ openb _ closeb])
  
  (= rbrackify (brackify "(" ")"))
  (= cbrackify (brackify "{" "}"))
  (= sbrackify (brackify "[" "]"))
  
  ...
  
  arc> (rbrackify "adm")
  "(adm")
  arc> (cbrackify "adm")
  "{adm}"
I suppose you could also write a macro, but I wouldn't bother:

  (def brackify (openb closeb)
    [+ openb _ closeb])
  
  (mac defbrackify (name open close)
    `(= ,name (brackify ,open ,close)))
  
  (defbrackify rbrackify "(" ")")
  (defbrackify cbrackify "{" "}")
  (defbrackify sbrackify "[" "]")
  
  ...
  
  arc> (rbrackify "adm")
  "(adm")
  arc> (cbrackify "adm")
  "{adm}"

-----

6 points by rntz 5625 days ago | link

The multiple '=s are unnecessary:

    (= rbrackify (brackify "(" ")")
       cbrackify (brackify "{" "}")
       sbrackify (brackify "[" "]"))

-----

2 points by twilightsentry 5618 days ago | link

What about a macro something like:

  (mac =map (f . args)
    `(= ,@(mappend (fn ((v . xs))
                     `(,v (,f ,@xs)))
                   args)))

  (=map brackify
    (rbrackify "(" ")")
    (cbrackify "{" "}")
    (sbrackify "[" "]"))

-----

1 point by thaddeus 5624 days ago | link

can someone explain to me how the variable adm is being passed into the function when it's not accounted for in the functions input args ?

Also - anyone notice there's now vote down buttons on the forum?

-----

4 points by absz 5624 days ago | link

The brackify function returns the closure [+ openb _ closeb]. The [... _ ...] notation means "construct an anonymous function of one argument, _"; it's the same as (fn (_) (... _ ...)). Thus, (brackify "(" ")") returns a function of one argument which, when called, surrounds its text with "()"; the text given is "adm".

The downvote buttons have been there for quite a while for me---you seem to have just broken 100 karma, so maybe it's because of that?

-----

1 point by thaddeus 5624 days ago | link

I see - thanks. T.

-----

1 point by adm 5625 days ago | link

thanks.

-----

3 points by rntz 5624 days ago | link

    brackify = lambda openb, closeb: lambda val: openb + val + closeb
The python code could also be shorter :).

-----