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.

Filter by
Sorted by
Tagged with
0 votes
1 answer
69 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[];...
einpoklum's user avatar
  • 115k
0 votes
1 answer
39 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 ...
Gabe_A's user avatar
  • 1
4 votes
1 answer
38 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 ...
Lyndon Gingerich's user avatar
2 votes
1 answer
130 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 ...
einpoklum's user avatar
  • 115k
0 votes
0 answers
34 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; ...
curious's user avatar
  • 123
0 votes
0 answers
43 views

When writing a cross-platform library, how to access the internal handle without exposing it to the users?

I'm trying to write a cross-platform library in Rust. I use a pattern similar to what the crate std does with the fs module In this example, assume that each platform have a different Player handle: ...
Feeps's user avatar
  • 1
-1 votes
1 answer
45 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 ...
dhakkan's user avatar
0 votes
1 answer
186 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 ...
PrzemekTom's user avatar
  • 1,142
4 votes
2 answers
160 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 ...
einpoklum's user avatar
  • 115k
0 votes
0 answers
25 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 ...
Paul Jurczak's user avatar
  • 6,839
6 votes
2 answers
205 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 ...
einpoklum's user avatar
  • 115k
0 votes
0 answers
9 views

Do exist a repository with language's dictionary txt file to create a c# dictionary?

As the tile a list of all words in this format: "food", "cibo" \n "air", "aria" ... and so on. Thanks in advance
Renato Tarabella's user avatar
0 votes
1 answer
89 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) { ...
John Passaniti's user avatar
3 votes
0 answers
316 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. ...
einpoklum's user avatar
  • 115k
0 votes
2 answers
163 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 ...
DL33's user avatar
  • 164
1 vote
1 answer
191 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, } #...
user3690467's user avatar
  • 3,017
1 vote
1 answer
60 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 ...
von spotz's user avatar
  • 835
1 vote
0 answers
60 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 │ ├── ...
Marc's user avatar
  • 41
0 votes
0 answers
31 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&...
einpoklum's user avatar
  • 115k
1 vote
0 answers
45 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 ...
Aaron V's user avatar
  • 6,566
-2 votes
2 answers
46 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 ...
Sergey Bolshakov's user avatar
1 vote
1 answer
67 views

Scala: idiomatic way to chain multiple copy() updates to immutable case class

I have an immutable configuration class, which can be only changed by constructing a copy of it using copy() call. The main for its construction is all good, but I also have an auxiliary flow, where ...
GreyCat's user avatar
  • 16.5k
1 vote
1 answer
57 views

Right way to get var[a][b][c] when keys may not exist

I have a nested data structure (a DynamicRecord, but I think it might as well be a nested list or anything else you can index with object.__getitem__) and would like to extract a value from it. Let’s ...
Charles's user avatar
  • 11.2k
3 votes
1 answer
62 views

How can one access Kotlin's `backtickedFunctions` from Java?

TL;DR: Is there a simple syntax in java to access kotlins backticked functions such as fun `if`(){...} Long Version: In Kotlin, one may write the following class. class ShapeShifter { fun speak() {...
Ar3s's user avatar
  • 2,237
0 votes
2 answers
58 views

Avoiding an extra space when detokenizing a non-range

I have a structure with many "options", each of which, depending on its value, translates into a command-line option - either with or without a value. The order of the command-line options ...
einpoklum's user avatar
  • 115k
0 votes
2 answers
175 views

Do sanity checks before or after calling a function? [closed]

What makes more sense in regard to performance, code size and idiomatic C++: Leaving sanity checks to the function or doing them beforehand to avoid even calling the function? Compare the following ...
glades's user avatar
  • 3,231
3 votes
1 answer
361 views

PowerShell equivalent of “dirname $0” from bash

I've used dirname "$0" which is an idiom to determine the path of the running script in bash, e.g.: pushd "$(dirname "$0")" data_dir="$(dirname "$0")/data/...
minhee's user avatar
  • 5,638
1 vote
1 answer
998 views

How to dynamically point to a static asset leveraging the path lookup in Vite/Vue3? Using Typescript paths in dynamic URLs to assets

It is my understanding that as per the docs, following is the idiomatic way to dynamically generate an url to a static asset with Vite/Vue3: URL(`../../assets/${name}.png`, import.meta.url).href ...
Zulan's user avatar
  • 21.8k
1 vote
1 answer
93 views

Why do C++ istreams only allow formatted-reading into an existing variable?

In C++ (and using the standard library facilities), if I want to read an integer from the standard input, I need to do this: int x; std::cin >> x; And looking at the std::istream page on ...
einpoklum's user avatar
  • 115k
0 votes
2 answers
1k views

How to create structs in Golang from other partial structs?

If I have a two different structs, that mostly overlap each other in regards to their property types, and I need to create one from the other, is there some more concise way to do so w/o having to ...
RavenHursT's user avatar
  • 2,326
2 votes
3 answers
329 views

Is there an alternative to the builder pattern that is preferred in C++?

I'm coming from Java where the builder pattern is used heavily, e.g. Foo foo = new FooBuilder() .setBar(43) .setBaz("hello, world!") .enableCache(true) .build(); Automapper ...
Andrew Cheong's user avatar
1 vote
1 answer
149 views

Being Idiomatic in code vs Dogmatic and why the distinction is important

After we finished the final in one of my C++ courses, there was one more optional lecture given (obviously the final was already done so most people didn't go), but I didn't have much else to do so I ...
Mrosky's user avatar
  • 13
0 votes
2 answers
633 views

'unzip' a Vec of tuples [duplicate]

So if I've got two vectors: let mut vec1 = vec![true, false, false, true]; let mut vec2 = vec![1.0, 0.0, 4.0, 2.0]; and I want to sort vec1 and vec2 together according to the floats in vec2, I can ...
beyarkay's user avatar
  • 410
8 votes
2 answers
309 views

What does `value >= value` do in JavaScript?

Below is one of conditional statements from the source code of d3.min. What is this checking for?: value >= value Here is the entire source code: export default function min(values, valueof) { ...
catwith's user avatar
  • 805
0 votes
2 answers
224 views

What is the idiomatic way to hardcode a byte vector with some metadata in a Rust module?

I am following the Rust wasm tutorial. in which you build a game-of-life clone and am currently doing the "Initialize the universe with a single space ship" exercise. To implement the ship I ...
Darvan42's user avatar
0 votes
1 answer
73 views

Longest prefix of an OCaml `string list` ending in a specific `string` value

I am trying to work out whether there is a particularly neat or efficient way of truncating a string after the final occurrence of a specific element. For my purposes, it is a monomorphized string ...
archaephyrryx's user avatar
-1 votes
1 answer
206 views

Is there a graceful approach to deserializing Go interface types? [duplicate]

Given the following: type Foo struct { Td ThingDoer // ... other stuff } type ThingDoer interface { doThing() } type doerA struct { AGuts string } func (a doerA) doThing() {} type doerB ...
NiloCK's user avatar
  • 571
3 votes
1 answer
1k views

Idiomatic way to handle errors with an early return in Rust

I currently have the below code to handle the case where I want to handle an error without propagation or continue the function. The use case for this is a web server controller, where I would prefer ...
JamesGill's user avatar
  • 173
0 votes
1 answer
164 views

What is the zsh idiom for using functions that can return success or failure as well as a list

I am looking for the "best way" or the accepted zsh idiom for creating and using functions that can return success or failure as well as a list or other text value. Currently I am doing this:...
pedz's user avatar
  • 2,241
-1 votes
1 answer
46 views

React Multilenguaje

Does React and the i18next package support languages ​​like Catalan, Basque, Galician, Valencian, etc? I use: import { useTranslation } from "react-i18next"; import i18next from "...
user2911197's user avatar
1 vote
1 answer
224 views

How to avoid key clone while updating and passing a HashMap in idiomatic Rust

I'm trying to write a piece of code that checks if an entry is in a cache, and if it isn't produce the value. The problem is that to produce the value, I'd like to pass along the cache because the ...
Snake's user avatar
  • 7,898
2 votes
2 answers
749 views

One line Array iterator javascript

I am coming from Python and I am looking for a single line iterator function for any array, where I can also check a condition and return a simple change to the items. Expected result should match the ...
Anupam Arya's user avatar
0 votes
0 answers
227 views

Managing global state from library

I'm writing a library in Rust that implements a certain struct and methods on it. I want, however, to expose to the consumer only the methods and leave the state variables hidden, with just a few ...
Gabriel Golfetti's user avatar
5 votes
1 answer
218 views

How to properly specify idiosyncratic ICC compiler options in CMake?

The Intel C/C++ has a bunch of custom flags, some of which mix compilation and linking, (such as -qopenmp), and others are just idiosyncratic alternative forms (such as -ipp for linking with Intel's ...
einpoklum's user avatar
  • 115k
3 votes
2 answers
964 views

What is the idiomatic way to convert a 1-tuple struct to the contained element?

Let us say we have the following type: struct Wrapper(Content); Say that I often need to access the Content value of this type, destructuring it every time gets cumbersome quickly. What would be the ...
Miguel Bartelsman's user avatar
1 vote
4 answers
638 views

Use of ternary operator instead of if-else in C++ [duplicate]

I just came across the following (anonymized) C++ code: auto my_flag = x > threshold; my_flag ? do_this() : do_that(); is this a standard C++ idiom instead of using if-else: if (x > threshold) {...
Peter K.'s user avatar
  • 8,018
0 votes
1 answer
714 views

Is cudaFree(0) guaranteed to do anything?

Mark Harris wrote here once - albeit 9 years ago by now - that: In fact cudaFree(0) is commonly used to initialize the CUDA context! and I see this (somewhat questionable) idiom used in this example ...
einpoklum's user avatar
  • 115k
1 vote
1 answer
216 views

if __name__ == "__main__": and recursion in Python [duplicate]

I had a confusion regarding if __name__ == "__main__": in Python and came across the same question on SO: What does if name == "main": do? Thanks to the most voted, detailed, and ...
Milan's user avatar
  • 1,703
-2 votes
3 answers
931 views

Golang idiom for passing multiple argument types

I am new to learning Go and have a question around defining an argument that could be one of two types. Take the code: type Thing struct { a int b int c string d string } type OtherThing ...
apr_1985's user avatar
  • 1,702
1 vote
1 answer
141 views

Multithreaded idiomatic find first of substrings in a string using modern C++

It is easy to find a string in a set of strings using set::find or first of a set of strings in a set of strings using std::find_first_of. But I think that STL doesn't handle this case of ...
omarekik's user avatar

1
2 3 4 5
24