On Aug 30, 3:24 am, Dan Fichter <[email protected]> wrote:
> [...]
> Take a dictionary of defaults and a user-supplied dictionary and return a
> new dictionary that combines them, with the user's entries winning when both
> dictionaries have the same key.
>
> [Clojure]
>
> (defn foo [defaults user]
> (merge defaults user))
>
> [Python]
> [...]
>
> def foo(defaults, user):
> d = {}
> for k, v in defaults.items() + user.items():
> d[k] = v
> return d
You don't need to explicitly build up a new list; using the dictionary
constructor will result in a fairer comparison. Clojure is still a
little nicer for having a built-in function.
def foo(defaults, user):
return dict(defaults.items() + user.items())
> [...]
> Define z as the lazy Cartesian product of two collections, x and y.
>
> [Clojure]
>
> (def z (for [i x j y] [i j]))
>
> [Python]
>
> def foo(x, y):
> for i in x:
> for j in y:
> yield i, j
> z = foo(x, y)
>
> import itertools
> z = itertools.product(x, y) # new in Python 2.6
>
> To get a lazy sequence in Python, you need to write a generator-function and
> then call it to get a generator, or use itertools.
That's not quite right; you could also use a generator expression. The
Clojure idiom that you made use of is directly available in Python:
((i, j) for i in x for j in y)
gives you a lazy sequence of entries in the Cartesian product of x and
y.
Best,
James
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---