Recent Questions - Programming Language Design and Implementation Stack Exchange most recent 30 from langdev.stackexchange.com 2023-12-09T01:02:58Z https://langdev.stackexchange.com/feeds https://creativecommons.org/licenses/by-sa/4.0/rdf https://langdev.stackexchange.com/q/3331 1 What are the potential consequences of allowing decimal-point-less number literals to be interpreted as floats? Rydwolf Programs https://langdev.stackexchange.com/users/5 2023-12-08T15:46:23Z 2023-12-08T22:14:30Z <p>In some languages, a number literal's type can be inferred from nearby expressions. For example, <code>1u64 + 2</code> might give a <code>u64</code> value of <code>3</code>, since the <code>2</code>'s type is inferred to be <code>u64</code>. This can similarly be done with floats/doubles. One language I've used that works like this is Rust; a number literal without a decimal point is an int, and a number literal with a decimal point is a float or double.</p> <p>However, this can make working with floats a little inconvenient. E.g., in a weakly typed language, I could write an expression like <code>(some_float + 1) / 2</code>; however, since <code>1</code> and <code>2</code> are int literals in Rust, this gives an error:</p> <pre><code>let out0 = (some_float + 1) / 2; ^ no implementation for f64 + {integer} </code></pre> <p>This makes it necessary to write something like <code>(some_float + 1.) / 2.</code>. So, my idea was to make number literals with a decimal point always act as floats/doubles, but allow decimal-point-less literals to be treated either as ints or floats.</p> <p>I'm not sure if there any languages which take this approach. Are there any potential downsides or ambiguities that could arise from this?</p> https://langdev.stackexchange.com/q/3330 -1 Should addition assignment a += b be equivalent to addition then assignment a = a + b [closed] Stef https://langdev.stackexchange.com/users/848 2023-12-08T14:55:09Z 2023-12-08T14:55:09Z <p>I am looking for the pros and cons of <code>a += b</code> being an exact synonymous, or not, of <code>a = a + b</code>. The question also holds regarding <code>a *= b</code> and <code>a = a * b</code>.</p> <p>I know that at least in Java and python3, they are not equivalent. I also know that in C#, they are equivalent, <a href="https://softwareengineering.stackexchange.com/questions/285366/why-it-is-not-possible-to-overload-compound-assignment-operator-in-c">even for custom classes</a>.</p> <p>I am mostly interested in arguments regarding the language design, and regarding the behaviour of <code>+=</code> for the language's built-in types.</p> <p>Arguments regarding good programming practices in object-oriented languages that enable the programmer to overload operators <code>+</code>, <code>=</code> and <code>+=</code> for their custom classes would be welcome too, were that part of the question not better-suited for <a href="https://softwareengineering.stackexchange.com">softwareengineering</a>.</p> <p>Here are two examples to showcase the difference of <code>a += b</code> and <code>a = a + b</code> in Java and in python3.</p> <p>First example. Compare the following two Java snippets, which illustrate how in Java, type conversion works differently depending on whether we multiply then assign the result, in two steps, or update a variable by multiplying it, in one step.</p> <pre class="lang-java prettyprint-override"><code>int x = 18; x *= 0.90; System.out.println(x); // 16 int x = 18; x = x * 0.90; System.out.println(x); // incompatible types: possible lossy conversion from double to int </code></pre> <p>Second example. Compare the following two python3 snippets, which illustrate how updating a variable with <code>+=</code> is different from rebinding the variable name to the result of an addition, at least in the case of a mutable type.</p> <pre><code>def f(b): b +=  print('b =', b) a = [1,2,3] f(a) print('a =', a) # b = [1, 2, 3, 42] # a = [1, 2, 3, 42] def g(b): b = b +  print('b =', b) a = [1,2,3] g(a) print('a =', a) # b = [1, 2, 3, 42] # a = [1, 2, 3] </code></pre> https://langdev.stackexchange.com/q/3327 4 Should bitwise operations have dedicated operators? [closed] dan04 https://langdev.stackexchange.com/users/968 2023-12-06T16:54:04Z 2023-12-06T22:15:06Z <p>Many programming languages have built-in support for <a href="https://en.wikipedia.org/wiki/Bitwise_operations" rel="nofollow noreferrer">bitwise operations</a>, often using C's syntax:</p> <ul> <li><code>~</code> = NOT</li> <li><code>&amp;</code> = AND</li> <li><code>|</code> = OR</li> <li><code>^</code> = XOR</li> <li><code>&lt;&lt;</code> = left shift (multiplication by power of 2)</li> <li><code>&gt;&gt;</code> = right shift (division by power of 2)</li> </ul> <p>These have various practical uses, for example:</p> <ul> <li>Using <a href="https://en.wikipedia.org/wiki/Bit_field" rel="nofollow noreferrer">bit fields</a> to pack multiple Boolean flags into a byte</li> <li>Cryptography (<a href="https://en.wikipedia.org/wiki/XOR_cipher" rel="nofollow noreferrer">XOR</a> is particularly convenient for this)</li> <li>Compression algorithms</li> <li><a href="https://en.wikipedia.org/wiki/Variable-length_quantity" rel="nofollow noreferrer">Variable-length quantity</a> encoding (including <a href="https://en.wikipedia.org/wiki/UTF-8" rel="nofollow noreferrer">UTF-8</a> character encoding)</li> </ul> <p>So, I would expect any general-purpose programming language to provide the standard bitwise <em>operations</em>. My question is: What's the benefit of them having dedicated punctuation-based <em>syntax</em>, in a language that's not specifically focused on low-level manipulation of binary data? Would there be a downside to relegating these operations to functions in the language's standard <em>library</em> (perhaps in a module named <code>bitops</code>)? This would free up <code>~&amp;|^</code> for other uses, e.g.,:</p> <ul> <li><code>^</code> could be a BASIC-style exponentiation operator, or a Pascal-style pointer type sigil.</li> <li><code>&amp;</code> could be a string/array concatenation operator, distinct from addition, so that you could have both <code>[1, 2] &amp; [3, 4] == [1, 2, 3, 4]</code> and <code>[1, 2] + [3, 4] == [4, 6]</code>.</li> </ul> <p>One argument for built-in bitwise operators is that they usually map directly to machine-language instructions, allowing efficient implementation. This may matter for performance-critical code, but is less of a concern for interpreted “scripting” languages.</p> https://langdev.stackexchange.com/q/3324 0 How to minimize total size of static data? Aster https://langdev.stackexchange.com/users/616 2023-12-06T11:54:14Z 2023-12-06T13:37:52Z <p>I am implementing a WASM backend and I hope to optimize the size.</p> <p>I have collected a series of static data. After erasing the type, it can be simply considered as <code>list&lt;u8&gt;</code>.</p> <p>However, these data may be repeated or partially covered. I hope to find a way to arrange them, so that the overall size will reduce.</p> <p>In other words, such a transformation:</p> <p><code>list&lt;list&lt;u8&gt;&gt; -&gt; (data: list&lt;u8&gt;, span: list&lt;(start: u32, length: u32)&gt;)</code></p> <p>But I don't know how to achieve this efficiently. And is there a special name for this kind of optimization?</p> https://langdev.stackexchange.com/q/3322 2 Possible ways to determine reach of implicit lambda expressions Lazar Ljubenović https://langdev.stackexchange.com/users/539 2023-12-06T08:16:54Z 2023-12-06T17:20:45Z <p>When defining an inline function, even the shortest way to do so usually requires naming its argument (unless you're going for the point-free style and you have an expression that returns a function).</p> <pre><code>// JavaScript arr.map(x =&gt; x + 1) // Rust iter.map(|x| x + 1) // Haskell map (\x -&gt; x + 1) arr </code></pre> <p>In maths, this is called “arrow notation”, e.g. <span class="math-container">$x \mapsto x + 1$</span>.</p> <p>This is already short and sweet, especially when you compare it to things like <code>function (x) { return x + 1 }</code>. But can we do better?</p> <p>An arguably less common way of defining functions in maths is using the “dot notation”, which looks like this: <span class="math-container">$(\;\cdot\;) + 1$</span>. Interpunct (the middle dot) is a common choice, but it's not a necessary one -- any symbol used rarely enough would work. The idea is to avoid giving any specific “common” name to a function argument, and to instead pick an esoteric one and stick with it.</p> <p>So I thought why not try this in a language.</p> <pre><code>arr.map(# + 1) </code></pre> <p>Researching, I've found out that Scala supports exactly this using <code>_</code>, and that Kotlin has something very similar using a reserved variable name <code>it</code>.</p> <pre><code>// Scala list.map(_ + 1) </code></pre> <pre><code>// Kotlin list.map { it + 1 } </code></pre> <p>A glaring question that comes up is how do you know how far out the implicit lambda reaches, i.e. do the examples above desugar into <code>x -&gt; list.map(x + 1)</code> or <code>list.map(x -&gt; x + 1)</code>.</p> <p>In Scala, desugaring happens up the syntax tree until the first pair of parentheses <code>()</code> is reached. In our case, that's the parenthesis for the function call, so the above snippet is what we intuitively expect.</p> <p>In Kotlin, <code>{}</code> is used in general to denote lambdas. For example, you could rewrite the above as <code>list.map { x -&gt; x + 1 }</code>. I'm not sure on the details, but apparently you can avoid writing the usual <code>()</code> parenthesis for function call if a lambda is the only argument to a function. So the full syntax sugar chain is <code>list.map({ x -&gt; x + 1 })</code> as <code>list.map { x -&gt; x + 1 }</code> as <code>list.map { it + 1 }</code>. So the scope is determined just like always: using <code>{}</code>.</p> <p>This shows two ways to determine the reach of an implicit lambda.</p> <p>Scala becomes tricky as soon as you have a more complex expression, where you want to use parentheses for grouping. Something as simple as <code>x -&gt; 2 * (x + 1)</code> cannot be expressed using <code>2 * (_ + 1)</code> because it would inwind into <code>2 * (x -&gt; x + 1)</code>, not <code>x -&gt; 2 * (x + 1)</code>. Kotlin's approach seems better as there's a pre-established delimiter pair so this kind of thing doesn't happen. This also plays nicely with tiny additional shortcuts you can take like collapsing <code>({})</code> into just <code>{}</code>. The price is the additional <code>{}</code> you have to introduce <em>everywhere</em>, so instead of <code>val f = x -&gt; x + 1</code>, you need <code>val f = { x -&gt; x + 1 }</code> (which is not necessarily <em>bad</em>, but since we're talking about a first world problem anyway, it's worth pointing it out as a con).</p> <p>What are other possible ways to determine the reach of a lambda expression, found in other programming languages (including non-mainstream ones)? What are their pros and cons?</p> https://langdev.stackexchange.com/q/3317 5 Correctness of mixed signed/unsigned arithmetic Matheus Moreira https://langdev.stackexchange.com/users/2098 2023-12-05T18:53:19Z 2023-12-06T13:17:01Z <p>I'm implementing signed and unsigned integers in my language. They are represented in C as <code>signed long</code> and <code>unsigned long</code> respectively.</p> <pre><code>struct value { enum type type; / SINT, UINT, ... */ union { signed long sint; unsigned long uint; /* more types... */ } as; }; </code></pre> <p>Basic arithmetic operations such as <code>+</code> and <code>-</code> may operate on integers of mixed signedness depending on the types of the operands:</p> <pre><code>struct value accumulator, argument; /* ... */ /* accumulator.type == UINT &amp;&amp; argument.type == SINT */ accumulator.as.unsigned_integer += argument.as.signed_integer; </code></pre> <p>This code causes the C compiler to emit warnings like:</p> <pre><code>warning: implicit conversion changes signedness: 'long' to 'unsigned long' [-Wsign-conversion] </code></pre> <p>Which makes me worried about the correctness of this implementation.</p> <p>I considered simply making it an error to operate on values of mixed signedness. I feel this would make the language too annoying to use though since the programmer would be required to defensively convert the integers every single time.</p> <p>I currently handle overflows by letting the values wrap around. I assume two's complement integer representation and compile with <code>-fwrapv</code>. I plan to implement overflow checks with transparent promotion to arbitrary precision integers in the future. I want to make integers work seamlessly just like they do in Python and Ruby.</p> <p>So is there a correct way to implement this? Any pitfalls and footguns I should be considering? How do other languages do it?</p> https://langdev.stackexchange.com/q/3311 10 How to tolerate syntax errors in a typed language? Hydroper https://langdev.stackexchange.com/users/606 2023-12-04T18:27:09Z 2023-12-05T16:17:07Z <p>In my tokenizers and parsers, once I find a syntax error (like an unexpected token) I usually throw a fatal exception that finishes parsing of the input source.</p> <p>The downside of how I usually do it is that:</p> <ul> <li>I do not get a resulting AST; everything parsed before the error is discarded.</li> <li>in a potential Language Server, I would normally not progress to type checking unless I cache the last type checking after a successful parsing of a program.</li> </ul> <p>I am aware that parsers like jQuery Esprima and <a href="http://www.github.com/oxyc/luaparse" rel="nofollow noreferrer">luaparse</a> (if I recall correctly) are able to tolerate these fatal syntax errors.</p> <p>I already use a diagnostics collection per Source, but most syntax errors throw a fatal exception. How can I tolerate such syntax errors (i.e. ignore the error and move to the next parsing)?</p> https://langdev.stackexchange.com/q/3309 -1 How to be (more) critical during Code Reviews of team members? [closed] Jay https://langdev.stackexchange.com/users/3310 2023-12-04T12:18:30Z 2023-12-04T12:18:30Z <p>I'm a Software Engineer who sometimes need to review the code of my fellow team members. I often look at the source code and think; this looks fine. I'm having a hard time to think critical about it. I can be very critical when writing code myself since I'm active/highly involved with the code, but looking at it more passively I'm not very good in reviewing the code. Aside from that I run the code, test it, it looks quite good for me. Any idea's how I can be more critical in Code Reviews?</p> https://langdev.stackexchange.com/q/3289 4 How can memory addresses be compile-time constants? user16217248 https://langdev.stackexchange.com/users/38 2023-12-03T00:30:22Z 2023-12-04T18:01:38Z <p>In C the memory address of a statically allocated object or a function is considered compile-time constant. For example this is valid code:</p> <pre class="lang-c prettyprint-override"><code>static int x; static int *const p = &amp;x; static const char *const s = &quot;The address of this string will not necessarily be the same across executions&quot;; </code></pre> <p>But since there is no way all implementations can guarantee that the actual address of even statically allocated objects can be known at compile time, how can they be <strong>treated</strong> as compile-time constants and used in places where a constant expression is required such as an initializer for other statically allocated objects? But they are more similar to <strong>runtime constants.</strong> What techniques do compilers use to initialize statically allocated pointers to addresses of other statically allocated objects?</p> https://langdev.stackexchange.com/q/3287 9 Are there languages that implement a more granular precondition system than just safe/unsafe mousetail https://langdev.stackexchange.com/users/8 2023-12-02T21:57:58Z 2023-12-05T19:55:24Z <p>In a language like C, many functions and operators have some preconditions to work. Violating a precondition is undefined behavior. For example, when indexing an array the index must be less than the length of the array. The compiler doesn't check this, it is up to the programmer.</p> <p>In Rust, most functions always have defined behavior. Some functions are unsafe and require specific preconditions. Violating these preconditions results in undefined behavior. For example the <a href="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.from_raw" rel="noreferrer"><code>Box::from_raw</code></a> method states &quot;For this to be safe, the memory must have been allocated in accordance with the memory layout used by Box.&quot;</p> <p>However, this is still not an ideal situation. Each unsafe method has it's own unique set of required conditions to work properly. People often use unsafe just assuming what a function will do, but without carefully reading the documentation you can easily introduce undefined behavior.</p> <p>Another issue is, suppose a unsafe function adds a precondition, there is no way to indicate this and check for it. For example, consider a hypothetical function that operates on pointers. It used to have some special case for null pointers but this is later deprecated and removed. Since the method is already unsafe existing code will still compile normally, just potentially fail in unexpected ways when used.</p> <h2>My question</h2> <p>I'm wondering if there is any more comprehensive safety system, that allows explicitly specifying pre-conditions in some structural way, then force users of the function to somehow acknowledge that they are aware of the requirements to run the code safely, in such a way that the code will break if a pre-condition is added which is not acknowledged.</p> <p>An example of something I was thinking:</p> <pre><code>function dereference(pointer p) requires that p is not null requires that p is aligned { ... } pointer p = get_pointer_from_somewhere() I promise p is aligned I promise p is not null dereference(p) </code></pre> <p>Or something like this:</p> <pre><code>function mutate_object(object o) requires the object is not mutated in a different thread for the duration of this function { ... } </code></pre> <p>I'm looking for prior art on the matter. Any languages that have something like this?</p> https://langdev.stackexchange.com/q/3286 9 What was the rationale for making realloc(ptr, 0) have UB in C23 user1345541 https://langdev.stackexchange.com/users/919 2023-12-02T18:23:30Z 2023-12-03T01:22:56Z <p>This is the first breaking change that C made, which was making <code>realloc(ptr, 0)</code> have UB instead of being roughly equivalent to <code>free(ptr)</code>.</p> <p>C has been known to be hesitant to making 'breaking' changes such as being extra careful to add <code>_Ugly</code> keywords that will not conflict with existing codebases.</p> <p>So why did they see it necessary to undefine <code>realloc(ptr, 0)</code>? What problems did requiring that to have defined behavior cause?</p> https://langdev.stackexchange.com/q/3284 11 Can sine converge to zero at infinity? Corbin https://langdev.stackexchange.com/users/715 2023-12-02T14:15:05Z 2023-12-05T01:08:21Z <p>In common languages, sine produces an error, NaN, or exception when evaluated at infinity. For example, in Python:</p> <pre><code>&gt;&gt;&gt; math.sin(float(&quot;inf&quot;)) ValueError: math domain error </code></pre> <p>However, consider the fuzzy nature of floating-point arithmetic. Large floating-point numbers are sparse and prone to rounding errors. As a result, sine is frustratingly inexact on large inputs:</p> <pre><code>&gt;&gt;&gt; math.sin(10**300) -0.8178819121159085 &gt;&gt;&gt; math.sin(10**300 + 1) -0.8178819121159085 &gt;&gt;&gt; math.sin(10**300 * math.pi) -0.902464352009667 </code></pre> <p>Consider an inexact large input as a continuous range. The average value of sine on that range is small, because most of the range covers pairs of peaks and troughs which cancel out to zero.</p> <p>So, suppose that we attenuate sine for large inputs. Specifically, we assign each large input a range, and divide the result of sine at that input by the number of wavelengths in that range (effectively the range divided by 2π); at (positive) infinity, we let sine converge to (positive) zero. What breaks or has counterintuitive behavior as a result?</p> https://langdev.stackexchange.com/q/3283 5 What goes wrong when division-by-zero is defined as multiplication-by-infinity? Corbin https://langdev.stackexchange.com/users/715 2023-12-02T13:55:14Z 2023-12-08T19:08:57Z <p>Sometimes, we want to implement floating-point operations on systems which use <a href="https://en.wikipedia.org/wiki/IEEE_754" rel="nofollow noreferrer">IEEE 754</a> representations of values, but don't necessarily support IEEE 754 semantics. For example, we may be using the <code>-ffast-math</code> compiler flag, or working with GPUs, DSPs, or other coprocessors. Additionally, suppose we lack <a href="https://en.wikipedia.org/wiki/NaN" rel="nofollow noreferrer">NaNs</a> or otherwise choose not to represent them.</p> <p>Even with <a href="https://en.wikipedia.org/wiki/Subnormal_number" rel="nofollow noreferrer">denorms</a>, zero is somewhat fuzzy, in the sense that (positive) zero represents both itself and also extremely small (positive) numbers. Similarly, infinity is somewhat fuzzy, in the sense that all overflowing computations round up to infinity.</p> <p>This suggests a fun answer to the question of division by zero. Define division of X and Y as multiplication of X and Y's multiplicative inverse, and define zero and infinity as multiplicative inverses. Then, division by zero is multiplication by infinity.</p> <p>Immediately, 0 / 0 = 0 × ∞ = 1, which might not be desirable; what else breaks or is counterintuitive?</p> https://langdev.stackexchange.com/q/3276 1 Implementing automatic derivation without macros? Jw C https://langdev.stackexchange.com/users/884 2023-12-01T08:28:21Z 2023-12-01T21:33:21Z <p>In Rust:</p> <pre class="lang-rust prettyprint-override"><code>#[derive(Display)] struct Foo&lt;T&gt;(T); </code></pre> <p>If <code>T</code> conforms to the <code>Display</code> trait, then <code>Foo&lt;T&gt;</code> can automatically implement <code>Display</code> using a macro.</p> <p>Is there an approach to accomplish this automatic implementation that doesn't rely on the macro system?</p> https://langdev.stackexchange.com/q/3274 2 How to assign unique names to variables within a function? Aster https://langdev.stackexchange.com/users/616 2023-12-01T03:09:22Z 2023-12-03T18:13:59Z <p>I want to promote all variables within the function to the top level of the function, make it more cache-friendly and reduce size bloat caused by alignment fill.</p> <p>In other words, it will roughly allocate a structure like this</p> <pre class="lang-rust prettyprint-override"><code>#align(4) struct FunctionArea { // fields of return value return: T3 // fields of input parameters in1: T1, in2: T2, // fields of local variables a1: A } </code></pre> <p>But I'm having trouble figuring out which local variables are needed.</p> <p>The difficulty is that I allow</p> <ol> <li><code>shadow variable</code>: the inner variable has the same name as the outer variable, but may occupy different spaces</li> <li><code>move variable</code>: variables have different names but occupy the same space</li> </ol> <hr /> <p>For example:</p> <pre class="lang-rust prettyprint-override"><code>fn f(in1: T1, in2: T2) -&gt; T3 { let a1: A = default; { let a1: A = default; // shadow let a2: A = a1; // move { let a2: A = default; // shadow let a3: A = a1.clone(); // not move } } } </code></pre> <p>This makes it impossible to use a simple counter to count which variables need to allocate memory space.</p> <h2>Question</h2> <p>How to accurately count which fields need to be created under <code>move</code> and <code>shadow</code> semantics?</p> <p>There is no need to consider constants.</p> https://langdev.stackexchange.com/q/3271 22 Why are volatile objects so difficult to work with in C++? Bbrk24 https://langdev.stackexchange.com/users/15 2023-11-30T18:47:29Z 2023-12-03T13:19:08Z <p>C++ does not generate default copy/move constructors or assignment operators for any <code>volatile</code> <code>struct</code> or <code>class</code> type. That is, given these three declarations, all of the following statements are illegal:</p> <pre class="lang-cpp prettyprint-override"><code>class Foo {}; // or struct Foo {}; Foo a; volatile Foo b; // ALL of these are illegal: a = b; b = a; Foo c = b; Foo d = std::move(b); volatile Foo e = b; b = b; // a=a is useless but allowed. b=b is not permitted. </code></pre> <p>Furthermore, if you define constructors and <code>operator=</code>s to allow these, then all the default ones go away, and you have to explicitly default them. Defining all this is a massive amount of boilerplate even for a small PoD class:</p> <pre class="lang-cpp prettyprint-override"><code>class Bar { int m_a, m_b; public: constexpr Bar(int a, int b) noexcept : m_a(a), m_b(b) {} // Everything below this line is the aforementioned boilerplate Bar(const Bar&amp;) = default; Bar(Bar&amp;&amp;) = default; Bar&amp; operator=(const Bar&amp;) = default; Bar&amp; operator=(Bar&amp;&amp;) = default; Bar(const volatile Bar&amp; other) noexcept : m_a(other.m_a), m_b(other.m_b) {} Bar(volatile Bar&amp;&amp; other) noexcept : m_a(std::move(other.m_a)), m_b(std::move(other.m_b)) {} Bar&amp; operator=(const volatile Bar&amp; other) noexcept { m_a = other.m_a; m_b = other.m_b; return *this; } volatile Bar&amp; operator=(const volatile Bar&amp; other) volatile noexcept { m_a = other.m_a; m_b = other.m_b; return *this; } Bar&amp; operator=(volatile Bar&amp;&amp; other) noexcept { m_a = std::move(other.m_a); m_b = std::move(other.m_b); return *this; } volatile Bar&amp; operator=(volatile Bar&amp;&amp; other) volatile noexcept { m_a = std::move(other.m_a); m_b = std::move(other.m_b); return *this; } }; </code></pre> <p>Why does C++ not generate these constructors and assignment operators for volatile types? Were they just considered unnecessary, or is there some technical reason they shouldn't exist by default?</p> https://langdev.stackexchange.com/q/3270 -2 How to Integrate Python with HTML? [closed] Dhruv Garg https://langdev.stackexchange.com/users/3242 2023-11-30T16:32:00Z 2023-11-30T16:32:00Z <p>I am a learner and am learning python currently. To know what all I have to learn I wanted to create a chatbot with algorithm that uses python. But I want that I have a input page to take commands through a HTMl Website. I have very basic knowledge of Javascript though I don't have problem learning more. I basically want to create it more like ChatGPT but I don't have data so maybe just a small version of it.</p> <p>I want Suggestions on how I can do this? Also, suggest places from where I can take courses for the execution of the same. And lastly, please suggest any books that a are very good for such things. Is there any algorithm mechanism I need to understand?</p> https://langdev.stackexchange.com/q/3269 2 What if all static methods in Java or C# could be extension methods just by default? terrorrussia-keeps-killing https://langdev.stackexchange.com/users/3241 2023-11-30T13:19:55Z 2023-12-01T08:32:49Z <p>C# 3.0 introduced extension methods to &quot;enhance&quot; behavior of existing types without interface bloating to avoid modifying/breaking existing interfaces. This was the first time I learned of such a concept. If I'm not mistaken after 15 years of not working with C#, extension methods are just static methods with their first parameters marked with <code>this</code> (so that it makes extension methods null-safe in terms of calling a method on &quot;this&quot;, but obviously static methods obey visibility rules).</p> <p>So are Kotlin extensions (have never worked with Kotlin, but Kotlin declarations look more natural to me though).</p> <p>In Java there is no such thing as extension methods (Java 8+ interface default methods are not merely syntax sugar), however <code>javac</code> plugins like Lombok or Manifold allow using extension methods right in Java.</p> <p>C#, Kotlin, and the Manifold plugin uses the declaration-site approach: the extension method declarations must declare they can be used as extension methods (Manifold, if I remember well, allows declare a whole class of extension methods at once). Lombok uses a call-site approach: the class using extension methods can inject all static methods from specific classes, as if all the injected methods were declared extension methods.</p> <p><s>I'm wondering, if all of these implementations use static methods, how would it affect if any scope-visible static methods could be merely used as extension methods not requiring extensions to be declared at declaration-site or call-site at all (<code>staticMethod(obj)</code> -&gt; <code>obj.staticMethod()</code>, or whatever non-dot like <code>obj.:staticMethod()</code>)? What implications might this idea have?</s></p> <p>I've just came across <a href="https://langdev.stackexchange.com/questions/265/advantages-of-extension-methods-vs-uniform-function-call-syntax-ufcs">this question</a> and the idea above seems to be equal to UFCS, so let me rephrase the question above: how would it affect Java and C# that both have mature codebases?</p> <p><sub>My question does not seem to be a duplicate of <a href="https://langdev.stackexchange.com/questions/1961/what-are-the-advantages-and-disadvantages-of-extension-methods">this question</a>.</sub></p> https://langdev.stackexchange.com/q/3267 0 What is best practice for a programming language which allows more than one syntax for class method invocations? [closed] Samuel Muldoon https://langdev.stackexchange.com/users/596 2023-11-29T23:47:47Z 2023-11-29T23:47:47Z <p>Consider the following code written in a syntax consistent with the programming language known as &quot;<a href="https://en.wikipedia.org/wiki/Python_(programming_language)" rel="nofollow noreferrer"><em><strong>python</strong></em></a>&quot;:</p> <pre class="lang-python prettyprint-override"><code>shp1 = Shape() shp2 = Shape() new_shape = shp1.join(shp2) </code></pre> <hr /> <p>What is best practice for a language which would allow all of the following syntaxes for invoking the any method (such as a method named <code>join</code>) of any class (for example, a class named something like <code>Shape</code>?)</p> <hr /> <pre class="lang-python prettyprint-override"><code>#--------------------------------------------------------------------------- new_shape = shp1.join(shp2) # Example One instance.method(*inputs) #--------------------------------------------------------------------------- new_shape = Shape.join(shp1, shp2) # Example Two class.method(*inputs) #--------------------------------------------------------------------------- new_shape = join&lt;Shape, Shape&gt;(shp1, shp2) # Example Three method&lt;class, class&gt;(*inputs) #--------------------------------------------------------------------------- new_shape = join&lt;type(shp1), type(shp2)&gt;(shp1, shp2) # Example Four #--------------------------------------------------------------------------- new_shape = join&lt;type(shp1.type()), shp2.type())&gt;(shp1, shp2) # Example Five #-------------------------------------------- ------------------------------- # COMMENCING DELIMITER OF Example Six t1 = type&lt;object&gt;(shp1) # Example Six A t2 = shp2.type() # Example Six B t3 = type(shp3) # Example Six C new_shape = join&lt;t1, t2, t3&gt;(shp1, shp2, shp3) # Example Six D # ENDING DELIMITER OF Example Six #--------------------------------------------------------------------------- </code></pre> <p>In general, whatever is to the left of the <code>.</code> becomes the left-most input argument for the syntax which resembles a global template function in <strong>C++</strong>.</p> <pre class="lang-None prettyprint-override"><code>result = x1.foobarbaz(x2, x3, x4, x5, x6, x7, x8, x9...) result = foobarbaz(x1, x2, x3, x4, x5, x6, x7, x8, x9...) </code></pre> <hr /> <p>All of the statements above show how to use the <code>join</code> method of the <code>Shape</code> class as function calls.</p> <p>Below, I will offer one different example of syntaxes for function definition (or method definition)</p> <pre><code>template &lt;typename T1, typename T2&gt; T1 join(T1 x1, T2 x2) { return T1() # returns new instance of type T1 using default constructor. } </code></pre> <p>The idea is to support a many-to-one relationship between input language syntax (interface syntax) and output (implementation language) syntax.</p> <p>What is best practice for allowing more than one syntax for method invocations?</p> https://langdev.stackexchange.com/q/3264 9 What is a "primary expression"? Lazar Ljubenović https://langdev.stackexchange.com/users/539 2023-11-29T22:40:30Z 2023-12-03T18:15:16Z <p>I've found that many grammars have a production called <code>PrimaryExpression</code> or something along those lines. <a href="https://tc39.es/ecma262/#prod-PrimaryExpression" rel="noreferrer">ECMAScript has <code>PrimaryExpression</code></a>, <a href="https://docs.python.org/3/reference/grammar.html" rel="noreferrer">Python has <code>primary</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/grammar" rel="noreferrer">C# has <code>primary_expression</code></a>, <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html" rel="noreferrer">Java has <code>Primary</code></a>, and many more I've seen over the years.</p> <p>It cannot be a coincidence that all these specifications have it. What is considered a &quot;primary expression&quot;?</p> <p>Maybe Haskell has one too, but <a href="https://www.haskell.org/onlinereport/syntax-iso.html" rel="noreferrer">I can't decipher which one it is</a>. If there's a primary expression, what's it called in their specification? If there's no primary expression, what's different about Haskell's syntax (or the way grammar is defined) that makes it stand out?</p> https://langdev.stackexchange.com/q/3261 -2 Low effort, high impact optimizations? [closed] Matheus Moreira https://langdev.stackexchange.com/users/2098 2023-11-29T20:57:17Z 2023-11-29T20:57:17Z <p><a href="https://en.wikipedia.org/wiki/Pareto_principle" rel="nofollow noreferrer">The Pareto principle</a> tells us that 20% of our efforts will bring us 80% of the results. The same should be true of optimizations.</p> <p>Are there optimization techniques out there that:</p> <ul> <li>Are simple and easy to implement; and</li> <li>Bring about disproportionate performance gains?</li> </ul> https://langdev.stackexchange.com/q/3258 -1 Why hasn't html a simple way of showing html tags as they are? [closed] Quora Feans https://langdev.stackexchange.com/users/2363 2023-11-29T19:39:04Z 2023-11-30T01:09:44Z <p>html comments meant to be read by the person reading the source are like <code>&lt;!-- Write your comments here --&gt;</code> But sometimes we want to depict a html as it is, for example show <code>&lt;b&gt;</code> to the end user and do not interpret the elemnt. Why the need to express this as <code>&lt;pre&gt;&amp;lt;b&amp;gt;&lt;/pre&gt; </code>? Why not a less convoluted way of doing this?</p> https://langdev.stackexchange.com/q/3254 11 What exactly is Pratt parsing used for and how does it work? Lazar Ljubenović https://langdev.stackexchange.com/users/539 2023-11-28T16:57:24Z 2023-12-01T03:11:39Z <p>I've come across the term “Pratt parsing”. The only thing I know is that it's an algorithm (or a pattern, a technique) used to parse expressions.</p> <p>How does it work? I'd like to see the intuition behind the algorithm, not just a series of steps to perform. What problems does this technique actually solve, and at what cost? How is it different from other well-known traditional/basic parsing strategies? Has it been “superseded” (at least in some aspects) by better techniques?</p> https://langdev.stackexchange.com/q/3252 26 Studies on learnability of braces vs. indentation for code blocks for beginners? Schmuddi https://langdev.stackexchange.com/users/1560 2023-11-28T08:29:02Z 2023-11-29T02:11:29Z <p>The discussion whether using indentation for code blocks is better or worse than using braces is an old one, but I don't want to rehash that discussion here (for reference, there was a fairly recent <a href="https://langdev.stackexchange.com/questions/33/what-are-the-drawbacks-of-using-indentation-for-code-blocks">question about the drawbacks of indentation</a> that summarizes some of the arguments).</p> <p>Instead, I'd like to know if there has ever been a systematic study on which of the two design choices is easier to learn for absolute programming beginners. I'm thinking of something like a study in which one group of participants (without any prior experience in programming) was taught a proto-language that featured code-block indentation. The other group of participants was taught a syntactically equivalent proto-language with the only difference that this language and the teaching material used braces instead of indentation. You could then compare the success of these participants in performing little coding tasks.</p> <p>I've searched for such a study, but was unsuccessful. Has any such study ever been published?</p> https://langdev.stackexchange.com/q/3244 5 Optimization algorithm using conditional invariants chrysante https://langdev.stackexchange.com/users/448 2023-11-27T11:24:15Z 2023-11-30T18:40:40Z <p>I am looking for an optimization algorithm that would make use of invariants in regions of code. For example</p> <pre><code>if (n == 0) f(n); </code></pre> <p>should be changed to</p> <pre><code>if (n == 0) f(0); </code></pre> <p>or</p> <pre><code>if (n &gt;= 0) { // ... if (n &lt;= 0) f(n); if (n &lt; 0) ... } </code></pre> <p>should be changed to</p> <pre><code>if (n &gt;= 0) { // ... if (n &lt;= 0) f(0); if (false) ... } </code></pre> <p>Now I could come up with an algorithm that does this for these simple cases (basically traverse a dominator tree of the function, keep track of all given conditions, annotate uses and then do a formal evaluation). But I wonder if there are any more general algorithms that do the above transform and perhaps more sophisticated optimizations.</p> <p>For example I could image this case:</p> <pre><code>if (i % 2 == 0) { bool cond1 = i % 3 == 0; bool cond2 = i % 6 == 0; } </code></pre> <p>Here <code>cond1</code> and <code>cond2</code> always have the same value and thus one computation can be elided, but I have no idea on how to implement such a transform.</p> <p>My compiler uses SSA form somewhat similar to LLVM IR.</p> https://langdev.stackexchange.com/q/3233 32 Why do common Rust packages depend on C code? StoneThrow https://langdev.stackexchange.com/users/3153 2023-11-25T04:30:23Z 2023-12-03T22:24:53Z <p>Chapter 1 of &quot;The Rust Programming Language&quot; (Klabnik and Nichols) says:</p> <blockquote> <p>[S]ome common Rust packages depend on C code and will need a C compiler.</p> </blockquote> <p>Why do Rust packages have any dependency on C code? That is, why does Rust code ever need to use something that isn't also written in Rust?</p> https://langdev.stackexchange.com/q/3231 1 Is there any way a Java-like language could implement immutable primitive arrays without incurring performance penalties? user16217248 https://langdev.stackexchange.com/users/38 2023-11-24T23:21:40Z 2023-12-03T00:47:18Z <p>I asked: <a href="https://softwareengineering.stackexchange.com/q/445737/404182">What prevents Java from having immutable primitive arrays?</a> a while back and got an answer: Because immutable primitive arrays would typically require checking some immutable flag every time a write attempt is made, slowing down performance.</p> <p>But I just thought, variables and references themselves can be made read-only (<code>final</code>). Yet they do not have a immutable flag associated with them (as far as I know), rather, they are checked at compile time. Would having a similar mechanism for immutable arrays be possible?</p> <p>For example, a mutable array reference could be converted to an immutable one but not vice versa, and thus any attempt made to write to an immutable array could be rejected at compile time, similar to other <code>final</code> items? Or are there edge cases that would make that not work out somehow?</p> <p>While this is technically having immutable views to arrays rather than actual immutable arrays themselves, is there any difference in practice between a <em>'true'</em> immutable array and an array created as an immutable view, so no non-immutable view exists? Either way, the array cannot and will not be modified.</p> https://langdev.stackexchange.com/q/3216 9 Do parsers typically need access to all tokens? Lazar Ljubenović https://langdev.stackexchange.com/users/539 2023-11-22T08:25:42Z 2023-11-28T21:36:55Z <p>Do parsers typically operate on the entire array/list of tokens available in memory, or are the tokens often streamed one by one as they are recognized? What influences the decision?</p> https://langdev.stackexchange.com/q/3204 20 What are the drawbacks of allowing implicit boolean/integer conversions? user16217248 https://langdev.stackexchange.com/users/38 2023-11-20T22:05:24Z 2023-12-03T18:31:57Z <p>Some languages (C, C++, JavaScript, Python) allow one to use integers as booleans and vice versa:</p> <pre><code>int x; if (x) // Equivalent to: x != 0 y(); </code></pre> <p>Or:</p> <pre><code>int x = 10 + (y &gt; 10); // Equivalent to: y &gt; 10 ? 11 : 10 </code></pre> <p>However, other languages such as Java, C#, and Swift disallow this. They do not even allow explicit casting and force users to explicitly write <code>!= 0</code> and <code>? 1 : 0</code> to cast from integer to boolean or boolean to integer respectively.</p> <p>What is the rationale for disallowing this? Allowing integers and booleans to freely convert allows certain logic to be expressed much more concisely, such as that to <a href="https://stackoverflow.com/a/65031220/16217248">determine if exactly N conditions are true</a>. So what are the drawbacks?</p> https://langdev.stackexchange.com/q/3149 14 What language was the first to treat null checks as smart casts to non-nullable types? Eldritch Conundrum https://langdev.stackexchange.com/users/875 2023-11-11T20:54:40Z 2023-11-30T10:45:45Z <p>As far as I know, for many decades, in mainstream programming languages, there were only two options to handle null-like optionality:</p> <ol> <li><p>Pointer or reference types are always nullable (the famous &quot;billion-dollar mistake&quot;). The programmer needs to remember to check for null wherever needed, or else the program does bad things at runtime. The compiler doesn't detect mistakes, though linters can often help.</p> </li> <li><p>There are separate &quot;optional&quot; or &quot;maybe&quot; wrapper types, so the programmer can't accidentally use a nullable value where a non-null value is required. This solves the problem of #1, but it means that the programmer has to introduce a new variable, with a different name, for the unwrapped value, even though it represents the same thing. (There can also be a runtime cost, if this is not compiled down to a pointer.)</p> </li> </ol> <p>In the 2010s (I think?), a new way appeared, which I love.</p> <ol start="3"> <li>Pointer or reference types are <em>usually</em> nullable, but the compiler requires a null-check where needed; it can do this because it's smart enough to detect that <code>x</code> is not null inside <code>if (x != null) { ... }</code>. This gives the safety guarantees of #2, without the downsides that I mentioned above. No downsides (that I know of).</li> </ol> <p>Kotlin calls that a &quot;smart cast&quot; (it works with downcasts in addition to null-checking). Swift has something similar too, requiring only adding a <code>let</code> keyword.</p> <p>This miraculous third way, which we will hopefully enjoy in every future language... This application of flow-sensitive typing to improve the ergonomics of safe null-checking... Which language did it come from?</p>