Questions tagged [idioms]
A programming idiom is the usual and customary way to write code in a particular language. Idioms are highly recognizable ways of overcoming a particular limitation and/or writing commonly-used code, sometimes with a purpose that is separate from the literal meaning of the code. An idiom can also be the standard way of implementing something when there are multiple ways to do it.
idioms
1,222
questions
0
votes
0
answers
46
views
How do you idiomatically DRY up rust code without upsetting the borrow checker?
Context
Coming from OOP I'm finding as I implement various traits and functions on my structs, I want to abstract bits and pieces of them out. But whenever I do, I run into borrow checker issues. I'm ...
7
votes
2
answers
385
views
Idiom for initializing an std::array using a generator function taking the index?
Suppose I have a function T foo(size_t i), And I want to construct an object arr of type std::array<T, N> such that arr[i] == foo(i). I would like a solution which works even when T is not ...
0
votes
0
answers
62
views
Most idiomatic way to increment a character in a string, '1' -> '2' etc
I am creating a fen representation of a chess state as part of my chess hobby project, and I was unable to come up with a safe solution for parsing the structure.
My current solution iterates through ...
1
vote
1
answer
36
views
kotlin KT-28061 for details for null safety on compiler
why cant I just
return s?.let{ it }?: {throw IllegalStateException("you got something screwed up...")}
for a function? from my understanding the compiler should be able to detect we either ...
1
vote
8
answers
134
views
Decent idiom for initializing an optional to either null or a value?
Motivation
With C++ having gotten optional's (in C++17), it is now common to want to write the equivalent of:
If a condition holds, initialize my variable with some expression; and if the condition ...
0
votes
1
answer
63
views
In Rust, what is the idiomatic way to associate members of one enum with other enum types and map between their integer and string representations?
Goal:
I'd like to turn a pair of (usagePage, usageID) integers to Rust enumeration variants and get the names of both the page and specific usages as strings for debugging purposes.
I'd like to ...
0
votes
0
answers
51
views
How to change calendar language on TextField type='date'
I am using React and Material-UI
I know about the existence of the LocalizationProvider and how I can use it to change the language of my DatePicker.
However, in my project, I must use TextField with ...
0
votes
1
answer
77
views
Functional way to implement this OO design with TypeScript
Suppose that I have the following design implemented in an OO language (e.g. Python). I know that the OO way is a bit unnatural and sometimes not preferred when using TypeScript. So what would be the ...
0
votes
2
answers
87
views
How to stop a call to map if nested find returns None?
I have the following struct:
struct Thing {
id: usize,
cost: u32,
numbers: Vec<usize>
}
I am considering the following three Thing objects and a vector chain_of_things that contains ...
0
votes
1
answer
40
views
How to factor out code into methods in a Ruby script while retaining access to the outer scope?
Suppose I have a Ruby script like the following to generate YAML describing a list of services:
require 'yaml'
environment_slug = ENV.fetch('CI_ENVIRONMENT_SLUG')
YAML.dump([
{
'name' => '...
0
votes
0
answers
38
views
How do I tell which of these ldd-reported libraries require allowance for via CMake?
Suppose I'm creating a target for an already-compiled library, foo.so. Now, this library has the following requirements/dependencies, as specified by ldd:
linux-gate.so.1 (0xf77d4000)
libm.so.6 => /...
1
vote
1
answer
85
views
Preventing Derived Class calling Base class's public method
I am writing a base class that provides a public update() method. When someone derives from this base class, they must implement a pure virtual method that controls a tiny bit of the behavior of this ...
0
votes
0
answers
14
views
Idiom for setting a variable in top-level scope
I have a CMakeLists.txt which sometimes serves as a project top-level list file and is sometimes used with add_subdirectory().
Now, for reasons, this file needs to set a variable in the top-level ...
0
votes
4
answers
81
views
How to best DRY with some ad-hoc class instances?
Sometimes in my code, I find myself wanting to define several instances of the same class, with the difference in the definition being small relative to its overall length, and sharing some common ...
1
vote
1
answer
223
views
Is there an idiomatic way of accepting particular children in React?
Suppose you have a Card component that takes content for the header, body and footer. One way to design it would be for consumers to use it like this:
<Card
header="foo"
body="...
0
votes
0
answers
17
views
CMake option naming convention for conditional parts/dependencies?
Is there a commonly-accepted convention regarding the naming of CMake options that indicate: "Depend on a certain package and build code utilizing that dependency"? And the same question for ...
0
votes
0
answers
34
views
Idiomatic way to do "find_package and download & build a fallback if not found"
I have a CMake project which requires package foo, with a certain version range.
Now, I don't want to force my own foo tarball into the project, nor always download a release from the Internet, i.e. I ...
0
votes
1
answer
61
views
Need some help understanding a couple of SCILAB idioms
Title pretty much covers it - I need some help understanding a couple of SCILAB idioms (Ultimate goal: convert some SCILAB code into Python)
Until today, I'd never heard of, let alone seen, SCILAB or ...
1
vote
1
answer
91
views
Is there a function in the Kotlin stlib for transforming a List<Pair<A, B>> into a Pair<List<A>, List<B>>
I currently have code with similar mechanics to the following
fun main() {
val listOfLists = listOf(listOf("1234", "1", "42"), listOf("hello", "there&...
1
vote
0
answers
95
views
Is there a way to use concise static dispatch inside a loop in Rust?
I have a for loop where the first iteration is a special case. The only difference is the type of one variable even though they both implement the same traits. I want to know if and how I can make it ...
1
vote
1
answer
81
views
What to do about exceptions which don't fit your Expected error type?
Suppose I want to use the new std::expected<T, E> mechanism offered in C++23, with a function:
using E = /* domain-specific error type regarding getting Foo's */
std::expected<Foo, E> ...
0
votes
0
answers
33
views
What is an idiomatic equivalent of simultaneously mutably and immutably borrowing sibling struct feilds in Rust? [duplicate]
I have a single game state struct - a monolith struct that has 2 feilds: a map, and a list of players. To update the player positions, I want a function that takes an immutable reference to the map, ...
0
votes
3
answers
93
views
How do I make a `Copy` value inaccessible after use?
struct S {
foo: i32,
// ... other fields
}
fn f(s: S) {
// transform foo
let new_foo = biz_logic(s.foo);
// from now on, the code should read `new_foo` whenever it needs `s.foo`,
...
6
votes
2
answers
724
views
Hidden Friend Concept in C++
I'm still a beginner in C++ trying to learn more about the language. I recently read about the concept of ADL (Argument-Dependent Lookup) and Hidden Friends idiom (https://www.modernescpp.com/index....
1
vote
1
answer
75
views
Was is the idiomatic way to define partial functions in Perl?
What is the most common/idiomatic way to define partial functions in Perl, that is functions that are not defined on all inputs. For example, in Haskell we have
safeHead :: [a] -> Maybe a
safeHead [...
1
vote
1
answer
52
views
CMake idiom regarding minimum microarchitecture checking
Suppose I have a CUDA project and I'm writing its CMakeLists.txt.
In my project, I have several .cu source files with kernels, each of which has a minimum NVIDIA microarchitecture version it supports.
...
4
votes
2
answers
1k
views
Is it better to return an Option<Vec<_>> or just an empty Vec<_>?
Suppose I am writing a function that takes a bunch of strings and filters out the "bad" ones.
The function then returns some strings, but there is a chance that all the strings are filtered ...
0
votes
0
answers
213
views
File structure for generated code in Rust
I'm generating protobuf code for my Rust project using the neoeinstein-prost buf plugin which, so far, is working well for my use case. My question is where is the idiomatic place for the generated *....
1
vote
0
answers
98
views
Is this n-ary weighted tree implementation idiomatic rust? I find it too repetitive
Context and description of the encountered problem
Currently I'm learning the Rust Programming Language and last weekend I found myself implementing a generic n-Ary weighted tree data structure whose ...
0
votes
0
answers
65
views
Custom ECMA Intl Locale for fictional language
TL;DR
I'd love to define once(/use everywhere) some custom Intl objects but I don't know if it's possible or if there is a good way to go at all ...
I need to use various custom (fictional) locales ...
3
votes
2
answers
162
views
Is it safe to swap two integers by `a, b = b, a` in golang?
package main
import "fmt"
func main() {
a := 1
b := 2
fmt.Printf("Before Swap: %v %v\n", a, b)
a, b = b, a
fmt.Printf(" After Swap: %v %v\n", a, b)
...
1
vote
1
answer
347
views
How does simple use of the asynchronous copy functionality differ in Hopper vs Ampere?
I understand that Hopper GPUs have a new piece of hardware named the "transfer memory accelerator". In this GTC 2023 session, we get an example of how to use it:
extern __shared__ int smem[];...
0
votes
1
answer
165
views
How to implement string pattern matching using a variety of inputs/modes in Rust
I ran into a problem with Rust's Pattern trait in relation to the str.find() method, in that if I tried to write a more flexible and complex function that USES str.find() I cant actually take a ...
4
votes
1
answer
59
views
When to add a unit argument to an existing function in F#
If I am already passing other parameters into a function, do I have any reason to pass in a unit argument as well, assuming the function is non-deterministic? Do I need to worry about memoization ...
2
votes
1
answer
149
views
Idiomatic replacement for a bespoke functor-with-callbacks class?
Background
If you're looking at some codebase, and you see something like:
class A {
virtual ~A() = default;
virtual void act() = 0;
};
you would likely say: "Oh, this is basically just ...
0
votes
0
answers
35
views
How can I return a struct with fields borrowed from the function returning it? [duplicate]
Suppose I have a function which returns a struct that contains a reference like so:
struct Foo<'a> {
x: &'a i32,
}
fn makeFoo<'a>() -> Foo<'a> {
let x = 30;
...
-1
votes
1
answer
74
views
Unable to successfully run packaged version of functional options pattern (FOP) that uses Go generics and embedded interfaces
In an effort to learn idiomatic Go, I am trying to write a reusable package (saybase for purposes of this question). This package provides a Base interface, with minimally required functions and a ...
3
votes
1
answer
973
views
How to write Dart idiomatic utility functions or classes?
I am pondering over a few different ways of writing utility classes/functions. By utility I mean a part of code being reused in many places in the project. For example a set of formatting functions ...
4
votes
2
answers
277
views
Should I use `std::uncaught_exceptions()` to decide whether to throw an exception from my dtor? [closed]
I have a class whose ctor makes a driver call, and whose dtor makes the matching terminating/release driver call. Those calls can fail. The problem is naturally with the dtor.
I am naturally aware of ...
0
votes
0
answers
28
views
Different behavior of a Python script in VSCode on Windows 10 vs. Ubuntu 22.04 [duplicate]
I'm using Version: 1.73.1 of VSCode with Python 3.10. This script:
from multiprocessing import Process
def foo(i):
print(i)
for i in range(12):
Process(target=foo, args=(i,)).start()
runs fine ...
8
votes
2
answers
1k
views
If we have ranges::zip and views::transform, why do we need ranges::zip_transform?
In C++23, the ranges (sub)library has gained std::ranges::zip, which zips multiple ranges into a single range of std::tuple's (or pairs). This is nice, and precludes requiring implementing this ...
0
votes
1
answer
102
views
C++ constructor on unnamed object idiom?
I have a C++ class that works like the Linux "devmem" utility for embedded systems. I'll simplify and give an outline of it here:
struct DevMem
{
DevMem(off_t start, off_t end)
{
...
4
votes
1
answer
1k
views
Should I use quotes or angle brackets for headers within same library?
Suppose I'm writing a library named foo, in C++. When installed to /some/where, it presents include files in /some/where/include/foo, and I expect the user to compile with -I/some/where/include.
...
0
votes
2
answers
748
views
How to concisely split string into 3 words?
Disclaimer 1: I am a complete beginner in Rust.
Disclaimer 2: this is a question mostly about codestyle. Call it "idiomatic" :)
I have a String. It should contain 3 words delimited by a ...
1
vote
1
answer
456
views
Is it idiomatic to use the From/Into trait for fallible conversions?
I am working on the auth system for my API using jwt and have the following two types:
#[derive(Serialize, Deserialize)]
pub struct UserClaims {
email: String,
exp: usize,
sub: String,
}
#...
1
vote
1
answer
71
views
Understanding an Axon library's Java Idiom involving Interface method and Lambda expression for configuration of TokenStore
I have a question on Java Syntax on lambda expressions and the java.util.function.Function Object. Also probably Spring Dependency Injection. It is an idiom that I don't know and I hope somebody can ...
1
vote
0
answers
110
views
How would a proper Rust code setup look like for database queries?
I am building a rather simple application that periodically writes data into a sqlite database. My src folder looks like this:
.
├── constants.rs
├── database
│ ├── db.rs
│ ├── error.rs
│ ├── ...
0
votes
0
answers
33
views
How to say "Depend on libfoo, dynamically if possible" in CMake
In CMake, I want to express the following: "target tgt should depend on libfoo. If libfoo is available as a dynamic library, great; otherwise, tgt should depend on the static version of libfoo&...
1
vote
0
answers
81
views
Idiomatically, should python context managers acquire resources at initialization, or when entered?
In general, I really like the explicitness of Python's context managers (CMs), but have been having trouble dealing with their inherent ambiguity. Specifically, without looking at a CM's code, it's ...
-2
votes
2
answers
99
views
Is it pythonic to use the '__main__' mechanism to test the module?
Suppose we have the following module:
# my_module.py
def my_sum(a, b):
return a + b + 1
if __name__ == '__main__':
s = my_sum(2, 3)
print(s)
How bad / good / pythonic is it to test my ...