idioms

Haskell: Is there an idiomatic way to insert every item in a list into its own list?

筅森魡賤 提交于 2019-11-27 07:47:21
问题 I've been using ((:[]) <$> xs) but if there is a more clear way I would love to use it. edit: so many good answers guys! I don't think I can accept one because they are all good. 回答1: I believe map return or map pure are good enough. 回答2: Maybe this? map (\x -> [x]) xs Yours can work on any functor I think so this would be more idomatic for just lists. 回答3: The split package provides a (Data.List.Split.)chunksOf function whose name is, IMO, more meaningful than the various map solutions (even

What is the clojure equivalent of the Python idiom “if __name__ == '__main__'”?

浪子不回头ぞ 提交于 2019-11-27 07:36:34
I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom. The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example: # mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() This is useful for simple, ad-hoc testing. One would normally use this

Python: most idiomatic way to convert None to empty string?

坚强是说给别人听的谎言 提交于 2019-11-27 06:05:56
What is the most idiomatic way to do the following? def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) update: I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple. def xstr(s): if s is None: return '' else: return str(s) If you actually want your function to behave like the str() built-in, but return an empty string when the argument is None, do this: def xstr(s): if s is None: return '' return str(s)

Common Ruby Idioms

纵饮孤独 提交于 2019-11-27 04:59:24
问题 One thing I love about ruby is that mostly it is a very readable language (which is great for self-documenting code) However, inspired by this question: Ruby Code explained and the description of how ||= works in ruby, I was thinking about the ruby idioms I don't use, as frankly, I don't fully grok them. So my question is, similar to the example from the referenced question, what common, but not obvious, ruby idioms do I need to be aware of to be a truly proficient ruby programmer? By the way

Python nested looping Idiom

别说谁变了你拦得住时间么 提交于 2019-11-27 04:30:21
I often find myself doing this: for x in range(x_size): for y in range(y_size): for z in range(z_size): pass # do something here Is there a more concise way to do this in Python? I am thinking of something along the lines of for x, z, y in ... ? : You can use itertools.product : >>> for x,y,z in itertools.product(range(2), range(2), range(3)): ... print x,y,z ... 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 1 0 0 1 0 1 1 0 2 1 1 0 1 1 1 1 1 2 If you've got numpy as a dependency already, numpy.ndindex will do the trick ... >>> for x,y,z in np.ndindex(2,2,2): ... print x,y,z ... 0 0 0 0 0 1 0 1 0 0 1 1 1

Union of dict objects in Python [duplicate]

三世轮回 提交于 2019-11-27 04:21:33
问题 This question already has an answer here: How do I merge two dictionaries in a single expression? 41 answers How do you calculate the union of two dict objects in Python, where a (key, value) pair is present in the result iff key is in either dict (unless there are duplicates)? For example, the union of {'a' : 0, 'b' : 1} and {'c' : 2} is {'a' : 0, 'b' : 1, 'c' : 2} . Preferably you can do this without modifying either input dict . Example of where this is useful: Get a dict of all variables

How to automatically register a class on creation

浪子不回头ぞ 提交于 2019-11-27 03:40:30
I was wondering whether a design pattern or idiom exists to automatically register a class type. Or simpler, can I force a method to get called on a class by simply extending a base class? For example, say I have a base class Animal and extending classes Tiger and Dog , and I have a helper function that prints out all classes that extend Animal . So I could have something like: struct AnimalManager { static std::vector<std::string> names; static void registerAnimal(std::string name) { //if not already registered names.push_back(name); } }; struct Animal { virtual std::string name() = 0; void

How do I manipulate $PATH elements in shell scripts?

≡放荡痞女 提交于 2019-11-27 02:53:02
Is there a idiomatic way of removing elements from PATH-like shell variables? That is I want to take PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:/path/to/app/bin:. and remove or replace the /path/to/app/bin without clobbering the rest of the variable. Extra points for allowing me put new elements in arbitrary positions. The target will be recognizable by a well defined string, and may occur at any point in the list. I know I've seen this done, and can probably cobble something together on my own, but I'm looking for a nice approach. Portability and standardization a plus. I use bash, but

DRY Ruby Initialization with Hash Argument

谁说胖子不能爱 提交于 2019-11-27 02:49:14
I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. What I end up doing is something like the following: class Example PROPERTIES = [:name, :age] PROPERTIES.each { |p| attr_reader p } def initialize(args) PROPERTIES.each do |p| self.instance_variable_set "@#{p}", args[p] if not args[p].nil? end end end Is there no more idiomatic way to achieve this? The throw-away constant and the symbol to string conversion seem particularly egregious. Mladen Jablanović You don't need the

avoiding the tedium of optional parameters

独自空忆成欢 提交于 2019-11-27 01:36:32
If I have a constructor with say 2 required parameters and 4 optional parameters, how can I avoid writing 16 constructors or even the 10 or so constructors I'd have to write if I used default parameters (which I don't like because it's poor self-documentation)? Are there any idioms or methods using templates I can use to make it less tedious? (And easier to maintain?) You might be interested in the Named Parameter Idiom . To summarize, create a class that holds the values you want to pass to your constructor(s). Add a method to set each of those values, and have each method do a return *this;