idiomatic

Idiomatic way to count occurrences in a collection of Options

左心房为你撑大大i 提交于 2020-06-14 06:56:12
问题 I want to count number of occurrences of a value in a collection of Options. let v = vec![Some(1), Some(1), Some(3), None]; v.iter() .filter(|Some(x)| x == &1) .count(); Doing this gives refutable pattern not covered error which makes sense. I got around this by doing v.iter() .filter(|x| x.is_some() && x.unwrap() == &1) .count() What's the idiomatic way to do this in rust? 回答1: You can use flatten to get rid of None and unwrap the Some(...) values. Code: let one_count = v.iter().flatten()

Pythonic custom sort for letter grades 'D', 'C-' ,…, 'A+'?

不羁岁月 提交于 2020-01-30 08:29:04
问题 Is there a more Pythonic, compact, intuitive way to sort letter-grades than this (without using a custom dict)? grades = ['B-','C','B','C+','A','D+','B+','C-','A+','D','A-'] sorted(grades, key=lambda g: (g[0], '+ -'.index((g+' ')[1])) ) ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'] In order to get the comparative numerical order of 'X-','X','X+', I do a hacky append of a space ' ' so that g[1] always exists, so then I can use .index() to get the rank of the modifier '+ -'.

Rust: Read and map lines from stdin and handling different error types

时光毁灭记忆、已成空白 提交于 2020-01-16 05:36:07
问题 I'm learning Rust and trying to solve some basic algorithm problems with it. In many cases, I want to read lines from stdin, perform some transformation on each line and return a vector of resulting items. One way I did this was like this: // Fully working Rust code let my_values: Vec<u32> = stdin .lock() .lines() .filter_map(Result::ok) .map(|line| line.parse::<u32>()) .filter_map(Result::ok) .map(|x|x*2) // For example .collect(); This works but of course silently ignores any errors that

What is the most idiomatic way to merge two error types?

◇◆丶佛笑我妖孽 提交于 2020-01-16 05:35:06
问题 I have a type Foo whose methods may "raise" errors of an associated type Foo::Err . pub trait Foo { type Err; fn foo(&mut self) -> Result<(), Self::Err>; } I have another trait Bar with a method intended to process a Foo . Bar may issue errors of its own (specified by an associated type Bar::Err ), but it may also encounter errors generated by the Foo it is processing. I can see two ways to do handle, but I don't know which one would be the most idiomatic to Rust. The first one embeds a

How do you rotate (circular shift) of a Scala collection

有些话、适合烂在心里 提交于 2020-01-13 08:48:34
问题 I can do this quite easily, and cleanly, using a for loop. For instance, if I wanted to traverse a Seq from every element back to itself I would do the following: val seq = Seq(1,2,3,4,5) for (i <- seq.indices) { for (j <- seq.indices) { print(seq(i + j % seq.length)) } } But as I'm looking to fold over the collection, I'm wondering if there is a more idiomatic approach. A recursive approach would allow me to avoid any var s. But basically, I'm wondering if something like the following is

With std::optional standardizing, can we stop using nullptr in new code and deprecate it? [closed]

两盒软妹~` 提交于 2020-01-07 05:46:06
问题 Closed . This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 2 years ago . From time immemorial, when passing pointers to or from functions, we tend to special-case the null pointer: p = get_pointer_to_the_foo(args); if (p == nullptr) { /* foo is inaccessible, do one thing */ } else { /* we can access foo, do something else */ } and this is an

What is the idiomatic way to swap two elements in a vector

烈酒焚心 提交于 2019-12-30 03:01:06
问题 Is there a better or more concise way to do the following? (defn swap [v i1 i2] "swap two positions in a vector" (let [e1 (v i1) e2 (v i2)] (-> (assoc v i1 e2) (assoc i2 e1)))) 回答1: I can't think of a particularly elegant solution, either. Here's how I'd write it though: (defn swap [v i1 i2] (asso­c v i2 (v i1) i1 (v i2)))­ 来源: https://stackoverflow.com/questions/5979538/what-is-the-idiomatic-way-to-swap-two-elements-in-a-vector

When is it appropriate to use an associated type versus a generic type?

微笑、不失礼 提交于 2019-12-27 10:39:47
问题 In this question, an issue arose that could be solved by changing an attempt at using a generic type parameter into an associated type. That prompted the question "Why is an associated type more appropriate here?", which made me want to know more. The RFC that introduced associated types says: This RFC clarifies trait matching by: Treating all trait type parameters as input types , and Providing associated types, which are output types . The RFC uses a graph structure as a motivating example,

How should I insert a value into the “middle” of another?

寵の児 提交于 2019-12-25 01:43:22
问题 I have two values v1 and v2 of types T1 and T2 respectively, with sizeof(T1)>sizeof(T2). Both types are plain-old-data. Now, I want to replace the k'th, k+1'th, ... k+sizeof(T2)-1'th bytes of v1 with the bytes of v2. C++ doesn't offer this functionality inherently in the language, nor to my knowledge in the standard library (at least, not directly). What would be the best approach to implementing this generically? i.e. implementing: template<typename T1, typename T2> void replace_bytes(T1& v1

Which way is ideal for Python factory registration?

给你一囗甜甜゛ 提交于 2019-12-23 17:25:27
问题 This is a question about which of these methods would be considered as the most Pythonic . I'm not looking for personal opinions, but, instead, what is idiomatic. My background is not in Python, so this will help me. I'm working on a Python 3 project which is extensible. The idea is similar to the factory pattern, except it is based on functions. Essentially, users will be able to create a custom function (across packages and projects) which my tool can locate and dynamically invoke. It will