Better HN
topnewbestaskshowjobs
Log inSign up

sparkie

2,329 karma · joined Feb 15, 2012 (14y ago) · 1,670 submissions

Submissions

comment 1d ago · link · parent

The standard is quite specific about what occurs when casting between integers and pointers.

> An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, may not be correctly aligned, may not point to an entity of the referenced type, and can produce an indeterminate representation when stored into an object.

> Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result is not required to be in the range of values of any integer type.

Why would these passages be written with such specificity, only to be overridden by unwritten passages w.r.t intptr_t?

When intptr_t was added, for C99, segmented memory was not uncommon, and there was more variation in processor architecture. The reason this is IDB or UB is because there were architectures where the implementation of such conversions is not straightforward.

Today we've largely converged on a common model of a single virtual address space with paging - if it were written today, it probably would have included such clauses, or made more assumptions about conversion between int/pointer rather than explicitly stating that nearly all behavior in this regard is IDB or UB, because the architectures these clauses were written to address - where implementation is non-obvious - are pretty much obsolete.

Anything besides this is subjective "interpretation" of the spec. There's nothing about `intptr_t` having different properties - the intptr_t is sufficiently wide to hold a pointer converted to integer - it solves only the last issue that "the result is not required to fit in the range of values of any integer type" - and hence why `intptr_t` is optional. It says nowhere that its purpose is to ensure that an intptr_t converted back to can be dereferenced without IDB. It's a pointer converted from an integer which is still subject to the constraints specified for int->pointer and pointer->int conversion.

Again, I don't challenge the idea that `void*->intptr_t->void*` is intended to result in a usable pointer - but I reject the idea that it was some kind of oversight to not explicitly state it in the spec - when the spec explicitly states the opposite - that it's IDB. It's implementation-defined because it was intended to be used in such way where pointers are effectively integers, but they did not want to place constraints on compilers which targetted the other architectures where making this guarantee would've been unpractical.

comment 1d ago · link · parent

> So your interpretation would also necessarily imply the standard doesn't guarantee you can dereference such a pointer.

It's not the same argument because the type in this case is still a pointer (which is not strictly an integer).

The standard is quite clear about conversion between pointers and integers.

> An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, may not be correctly aligned, may not point to an entity of the referenced type, and can produce an indeterminate representation when stored into an object.

> Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result is not required to be in the range of values of any integer type.

The purpose of `intptr_t` is to solve that last issue: it's an integer type sufficiently wide to hold a pointer, so that the result is in the range of values held by the intptr_t - and thus the round trip compares equal to the original pointer - but there's nothing else specified in the spec about intptr_t solving the other issues outlined in these clauses.

comment 1d ago · link · parent

Monetization isn't going to come from API pricing.

AI: Advertisements Incoming.

If AI is poised to overtake Google in search, it's going to overtake Google in ads too. The vast majority of people aren't going to pay a penny to ask questions - just like they don't pay to use gmail or hotmail. They'll pay with their data.

If you're old enough to remember using Google in its early days, it was fantastic - you searched something, it gave you what you searched for. The more ads started coming, the worse the search results became.

AI will probably suffer a similar fate - your clanker companion isn't going to give you the most relevant information related to your queries - it will be a salesman optimizing for the highest bidding advertisers, who obviously aren't going to keep paying Google if nobody is using it, are they?

The AI companies might pretend otherwise, but this is how they will all end up - they'll be forced by the market and shareholders - those who don't offer a free-to-use service backed by ads will become irrelevant over time. They will be training their AI at sales.

This is a big part of why they want regulatory capture. An AI you run on your own machine isn't going to try and sell you things you don't need. They need you to be using a data-collecting AI.

AI can probably do a far better job at advertising than Google can. It can know more about you from your conversations with it. It could subliminally sell you products or services that don't even look like ads, but are just casually dropped into a conversation. The bot might even try to convince you to buy a particular product, and it will know the best way to do so because it will be profiling you with every word you type - but it isn't going to be the most relevant product if the developer of that product isn't paying big money to BigAI.

comment 1d ago · link · parent

It would've been trivial for the committee to add such clause in the spec - why only the requirement that they compare equal and not that they dereference the same object?

The standard leaves a lot of things implementation defined deliberately to allow for flexibility in both processor design and compiler implementation.

I don't think for example, a segmented architecture shouldn't provide an `intptr_t` - it's still useful to be able to cast a pointer to integer and back even in the case of segmentation - but is obviously more prone to error if we dereference it in a different segment (which would be UB).

I completely agree that it is the intended case that a pointer that has had this round trip is intended to be dereferenced - but I disagree that the requirement to do so is an oversight and not a deliberate omission.

There are potential cases where you would want to dereference the pointer but to a different object (which is UB by the standard, but could be well defined for a specific compiler/arch). Consider for example, if you have a bunch of threads which all have the same structure in their thread local storage - it can be useful to be able to specify an offset that is going fetch a value specific value from the TLS - but obviously a different one in each thread - ie, we want the pointer to be an offset, and not an absolute address.

comment 1d ago · link · parent

Well, that was kind of my point.

"real" numbers are incomplete. If you allow the infinitesimals then the equations work out just fine and you can measure those small differences between the repeating decimals and rational numbers. "real" numbers are a subset of some other kind of number (eg, surreal numbers) - where the equality happens to work out with real numbers because ϵ = 0, then any Nϵ = 0 purely because multiplication by 0 = 0.

With surreal numbers, they're unequal because we're not just cancelling out all those ϵ. It's also why the common proof of 0.999... = 1 fails:

   x = 0.999...
   10x = 9.999...
This multiplication is false when infinitesimals are included, because x = 1 - ϵ, therefore 10x = 10 - 10ϵ - but 9.999... is 10 - ϵ, it's 9ϵ larger. "Real" numbers have magically added 9ϵ out of nowhere.

comment 1d ago · link · parent

The only stricter requirement in the standard is that they compare equal after the round trip.

The intended purpose of these types is to allow the round trip, yes, and the requirement they compare equal is part of that. The standard doesn't put stricter requirements. I don't think that is an oversight, but a deliberate omission to allow for flexibility in implementation.

It's up to the compiler to specify that it's safe to dereference the pointer after the round trip - the standard does not want to put such constraints on implementors.

comment 1d ago · link · parent

I think it's quite clear.

> An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, may not be correctly aligned, may not point to an entity of the referenced type, and can produce an indeterminate representation when stored into an object.

That isn't to say we can't do the cast - compilers specify the behavior, and most modern architectures have a linear virtual address space where the round trip is valid - though it may not always be - for example, with the fs/gs segment registers - a cast of pointer to integer isn't just a simple conversion of type - it must also fetch the value from the FS register and offset the pointer by this to produce an integer containing the absolute address. This is entirely implementation defined.

Producing the absolute virtual address of a `thread_local` is potential UB though - if you attempt to dereference it in a different thread.

Another example would be casting a qualified pointer (const, restrict, volatile) to an integer, then back to a pointer with a different qualifier or no qualifier - then dereferencing such pointer would of course be UB as per the standard - the cast to `intptr_t` loses information about its qualification - but the pointers would still compare equal - as the standard guarantees that a pointer cast to a qualified pointer compares equal.

comment 1d ago · link · parent

You can interpret it as uintptr_t - particularly now that the latest C standards require two's complement representation of integers - but pointers on amd64 are more like signed ints.

The sign bit must match the highest bit of the virtual address (47th bit counting from 0 in the case of 4LP, or the 56th bit for 5LP). (And without LAM/UAI, all the bits in between must match too.)

Eg, with 4LP, if you cast a pointer to `uintptr_t`, shift it left 16 bits, then shift right 16 bits - then an address in the higher half (usually in the Kernel) would be non-canonical. Do the same for `intptr_t` it will be canonical because the shift right is an arithmetic shift.

On other architectures this isn't the case. I know AARCH64 for example does not use canonicalization. If you were doing the same shift left/right by 16 as above on AARCH64, you'd want a uintptr_t.

comment 1d ago · link · parent

The C standard does not make any guarantees that you can dereference it.

And x86-64 is arguably still "segmented" in that you can use the FS and GC segment registers (they're typically used for TLS). Eg, if you cast a `thread_local` pointer to `intptr_t` - the standard makes no requirement that it point to the absolute virtual address (though this is the common implementation choice by GCC etc).

comment 1d ago · link · parent

Arguably they're more like signed integers in the case of amd64 - due to address canonicalization. Eg, with 4-level paging we have a 48-bit address space, and valid pointers have the signed integer values `-2^48..+2^48-1`.

They can be further complicated by UAI/LAM, which relaxes the canonicalization constraints and allows bits 48..62 (the high bits, excluding the sign bit) to be anything - so we can have pointers that compare unequal but point to the same address - a potential source of exploits (There's already been Spectre-like vulnerabilities shown for LAM). Fortunately nobody really uses LAM - it needs enabling by the kernel to be used in user space to begin with.

comment 1d ago · link · parent

> I'm not sure if C even requires a pointer to be just a linear address, as opposed to something structured.

It doesn't. The standard does not require any particular representation for pointers. It does specify that addition and subtraction on them is possible - but does not specify how this occurs - only that for example, if you have an array `int x[]`, then `x + 1` should point to the second item (index 1) in the array.

comment 1d ago · link · parent

If you convert a pointer to `intptr_t`/`uintptr_t` and back again to a pointer, the standard only guarantees that it compares equal to the original - but it makes no guarantee that you can dereference that pointer.

For example, if you had a system with segmented memory, you could cast a pointer used in one segment to `intptr_t`, change the segment register, then attempt to cast back to a pointer and dereference it, which of course is UB.

Pointers are not merely bit vectors. Their representation depends on architecture, and there's no guarantee that they even have an integer representation (intptr_t/uintptr_t are optional) - and even if they do have an integer representation, there's no guarantee that this is a complete enough representation to use the pointer - eg, with the segmentation example above - the `intptr_t` does not contain the segment information.

The examples work as one would expect because they're being run on a system with a single linear virtual address space, where pointers can be represented by an integer. The compiler for such platforms may specify what behavior is to occur in these cases - but the C standard does not.

comment 2d ago · link · parent

There's trivially a number between them if we don't discard infinitesimals - 1.999... / 2.

    0.999... = 1 - ϵ
    1.999... = 2 - ϵ
    (2 - ϵ) / 2 = 1 - ϵ/2
    1 - ϵ < 1 - ϵ/2 < 1
    0.999... < 0.999... + ϵ/2 < 1
If you just say "all infinitesimals are zero", then 0.999... = 1 only because ϵ = 0 and therefore 1/2ϵ = 0.

comment 3d ago · link · parent

Consider, intuitively:

    1 - 0.9 = 0.1       (1 / 10^1) [1 dp]
    1 - 0.99 = 0.01     (1 / 10^2) [2 dp]
    1 - 0.999 = 0.001   (1 / 10^3) [3 dp]
    1 - 0.9999 = 0.0001 (1 / 10^4) [4 dp]
    ...
    1 - 0.999... = ???  (1 / 10^∞) [∞ dp]
For `n` digits after the decimal point, the difference between 1 and .9[n] is always 1/10^n. Why would it not also be for infinity?

Lets suppose 1/10^∞ is a number (obviously not a real number, but a number nonetheless). Call it ϵ

    0.999... = 1 - ϵ
Now, lets look at this common "proof", using this

    x = 0.999...
    10x = 9.999...      [by multiplying by 10]
    10x = 9 + 0.999...  [by splitting off the integer part]
    10x = 9 + x         [by definition of x]
    9x = 9              [by subtracting x]
    x = 1               [by dividing by 9]
There's a flaw here on the second line: The assumption that 10 * 0.999... = 9.999...

    x = 0.999...
    x = 1 - ϵ            [by assuming ϵ is a number]
    10x = 10 - 10ϵ       [by multiplying by 10]
    10x = 9 + (1 - 10ϵ)  [by splitting off the integer part]
    10x = 9 + x - 9ϵ     [by definition of x]
    9x = 9 - 9ϵ          [by subtracting x]
    x = 1 - ϵ            [by dividing by 9]
In the original proof, they're silently adding 9ϵ to the result when multiplying by 10.

   10x = 9.999... = 10 - ϵ
Which of course is incorrect. 10*(1 - ϵ) = 10 - 10ϵ, by usual mathematical convention. Where did the additional 9ϵ magically appear from?

The original "proof" assumes that ϵ = 0 and therefore 10ϵ = ϵ

But if ϵ is not 0, then the proof falls apart, because 10ϵ != ϵ

So 0.999... = 1 iff ϵ = 0

Does 1/10^∞ = 0?

For real numbers, it's just a given. You must simply accept it and move on.

comment 3d ago · link · parent

The trouble is that definition isn't clear. We're told that `...` means "repeat the last 3 digits" - this isn't the same as saying "it refers to the number it approaches" - in fact, mathematicians are the source of the confusion because they refuse to admit that repeating a decimal ∞ times is a way of expressing a limit.

For any finite N, we can say:

    repeat_N_times(n : Nat, sum : Real, decimal : Real) =
        if n == 0 or decimal == 0 then 0
        else repeat_N_times(n - 1, sum + decimal, decimal / 10)

    f(n, decimal) = repeat_N_times(n, 0, decimal)
So eg,

    f(_, 0.0) = 0 [for any N]

    f(1, 0.9) = 0.9
    f(2, 0.9) = 0.99
    f(6, 0.9) = 0.999999
Obviously, if we give ∞ for n when the decimal is nonzero, the function never terminates, but, the sum also never reaches 1 - since each successive call only closes the gap by 9/10th the difference between the previous sum and 1.

So, we can specify that

    lim   f(n, 0.9) = 1
    n->∞
In other words,

    0.999... = lim   f(n, 0.9) = 1
               n->∞
But f(∞, 0.9) and 0.999... are two equivalent ways of expressing an "infinitely repeated 9" after the decimal point.

So does `...` refer to an infinitely repeated decimal, or does it not? Are f(∞, 0.9) and 0.999... equivalent?

If not, then 0.999... is clearly not just a "repeated decimal", because that's what `f(∞, _)` is - by inductive definition.

So, we should either stop calling `...` a "repeating decimal" or accept that repeating decimals represent limits.

If we accept that repeating decimals are limits (they are), then nobody need challenge that 0.999... = 1 - it's obviously true.

Tell that to a mathematician and they say: NO! Repeating decimals are not limits!

comment 3d ago · link · parent

It's a process, because for any terminating number, if you multiply it by 10, it shifts a zero in on the right.

  0.9 * 10 = 9.0
But for non-terminating numbers, they shift something non-zero in on the right when multiplied by 10.

  0.999... * 10 = 9.999...
Also, consider something like:

  1.999... / 2
For any terminating sequence of .999, the result shifts a 5 in on the right

  1.99 / 2 = 0.995
But for non-terminating sequence, it shifts in another 9.

  1.999... / 2 = 0.999...
How do you explain this without a process?

---

Intuitively:

  1 - 0.9 = 0.1        (1 / 10^1) [1 decimal place]
  1 - 0.99 = 0.01      (1 / 10^2) [2 decimal places]
  1 - 0.999 = 0.001    (1 / 10^3) [3 decimal places]
  1 - 0.9999 = 0.0001  (1 / 10^4) [4 decimal places]
Then for an infinite number of decimal places:

  1 - 0.999... = 1 / 10^∞
So for 0.999... = 1, you have to convince someone that 1 / 10^∞ = 0

Which is true in standard analysis - there are no non-zero infinitesimals - but there are other number systems besides the reals which do have infinitesimals.

While I accept that 0.999... = 1 in standard analysis, it is not at all intuitive to me that 0.999... is a number and not a limit.

---

Suppose we write a function to produce a number with `n` 9s after the decimal point:

    f'(n, sum, dec) = 
        if n == 0 || dec == 0 then sum 
        else f'(n - 1, sum + dec, dec / 10)
  
    f(n) = f'(n, 0, 0.9)
Then its clear that

    f(1) = 0.9
    f(2) = 0.99
    f(3) = 0.999
    ...
For any `n`, the result will never reach `1`. Each successively larger `n` only ever closes 9/10ths of the gap. There is no way to close that extra 1/10th of the gap.

By definition of `...` meaning "repeat the previous 3 digits an infinite number of times", we can accept that f(∞) = 0.999... - two different ways to specify the same thing - a non-terminating sequence of 9s after the decimal point.

It's only intuitive to me then that:

    lim   f(n) = 1
    n->∞
Since no single `n` can actually ever produce 1. Even f(∞) < 1, as we didn't include any clause that specifies if n = ∞, add in the additional, 1/10th the difference between the sum and 1.

If you plot f(n), you will see quite clearly that it's an asymptote that approaches 1 as n->∞

If repeated decimals are limits, it makes perfect sense. The claim that `0.999...` is not a limit, but just a number, is why its unobvious that 0.999... = 1

comment 3d ago · link · parent

Think of it like a recursive process which terminates for 0, but produces an infinite recursion for anything else.

    repeat_digit(x) = x / 10 + repeat_digit(x / 10)
Since 0 / 10 = 0, 0.0 / 10 = 0, and 0.000 / 10 = 0, and 0 + 0.0 + 0.000 = 0, etc - we know that this produces 0 and could short circuit it to terminate - maybe clearer instead to write:

    repeat_digit(x) =
        if x == 0 then 0
        else x / 10 + repeat_digit(x / 10)

    repeat_digit(0) = 0        ;; terminates
    repeat_digit(9) = 0.999... ;; never terminates

comment 3d ago · link · parent

The same assumption that 0.999... = 1 is used to state that 0.333... = 1/3.

Someone who doesn't believe the former won't believe the latter.

There are also non-standard analyses where 0.999... ≠ 1 - when you include non-zero infinitesimals like with hyperreal/surreal numbers.

comment 2w ago · link · parent

In some languages (eg, on dotnet), tagged unions are implemented through an OOP hierarchy, where you have, for example, something like:

    public sealed abstract class Option<T> {
        private Option() { }
        public sealed class Some<T> : Option<T> {
            private readonly T value;
            public Some(T value) {
                this.value = value;
            }
        }
        public sealed class None<T> : Option<T> {
            public None() { }
        }
        public static Option<T> Some(T value) { return new Some(T); }
        static readonly Option<T> _None = new None();
        public static Option<T> None() { return _None; }
    }
Where you can use `Option.Some` or `Option.None`, and the return type is inferred from the parameter.

The sizeof(None) is not the same as sizeof(Some<T>) - the Some class has an additional field not present in the None class - and the size of Some depends on the type parameter T.

If the objects have RTTI, we don't even need a tag field, as there is an implicit tag in the form of type information in the object - the pattern matching facility can test `opt is Some<T>` or `opt is None`.

In C we would have to use a pointer to option to do the equivalent, eg with some GCC extensions we can do:

    enum option_tag { OPT_NONE, OPT_SOME };
    typedef struct option { enum_option_tag tag; } *Option;
    struct none { struct option base; } _none = { .base.tag = OPT_NONE };
    Option None = (Option)&_none;
    
    #define Some(T, _value) \
        ({ \
            struct some_##T { \
                struct option base; \
                T value; \
            } *result = GC_alloc(sizeof(struct some_##T)); \
            result->base.tag = OPT_SOME; \
            result->value = (_value); \
            (struct option*)result; \
        })

    bool is_some(Option opt) { 
        return opt->tag == OPT_SOME;
    }
    bool is_none(Option opt) {
        return opt->tag == OPT_NONE;
    }

    #define _get_some(T, opt) (((struct some_##T*)(opt))->value)
This ONLY works if the tag is the first field - casting between pointers to different types is UB if the first fields are not the same.

Not the most efficient way to implement an Option in C, but for other tagged unions, if any of the values are particularly large this may be beneficial.

comment 2w ago · link · parent

IMO, a bad idea.

It's a bit like putting the length of an array at the end rather than the beginning though - you need to know its size first to know the offset.

The value of a tagged union may be like a flexible array member - in that the size of the value depends on the tag. We shouldn't need to allocate the maximum possible variant's space when most of the instances may be the smallest. Unlike a C `union`, which are a fixed size, a tagged union has no such requirement - it can be dynamically sized depending on tag.

comment 3w ago · link · parent

If you don't need insert/remove in middle, only at the end, there are more optimal data structures for Lists like RAOTS[1].

Btrees are O(log n) random access, O(log n) cons and use O(log n) excess space.

Unrolled linked lists are still O(n) random access because we ignore the constant factor of block size. They also use O(n) excess space for pointers, but have O(1) cons.

RAOTS are O(1) random access, O(1) amortized cons [O(√n) worse case], and use O(√n) excess space.

RAOTS is basically a tree of depth 1. The root is an "index block" of pointers to data blocks which grow in size proportional to the square root of the data length (similar to Hashed Array Trees, but doesn't require restructuring on each power of 2). The index block has length ~√n.

The square root is an approximation - the structure grows in "superblocks" where each superblock has `~√n` blocks of size `~√n` The pattern is: [1x1, 1x2, 2x2, 2x4, 4x4, 4x8, 8x8, 8x16, 16x16, 16x32, ...] Even indexed superblocks double the data block size, odd indexed superblocks double the number of blocks per superblock. It doesn't use an actual `sqrt()` call uses but some bit tricks via `clz`.

A simpler trick, which has no single name but have been known as "segmented lists", is where the index block points to blocks increasing in size geometrically, essentially like a dynamic array but where we don't need to `realloc`. The index block is length 1+log₂n and each index i points to a block of length 2⁽ⁱ⁻¹⁾. These have O(1) random access, O(1) amortized cons [O(n) worst case] and waste O(n) space [with constant factor of 1/2]. The random access is very efficient as it's only two dereferences and a few bit tricks:

    index_block[bit_width(idx)][idx - bit_floor(idx)]
This is more cache friendly than the other approaches.

There's also Bagwell's VList[2] which is like a mashup of the "segmented list" and an unrolled list - the blocks grow geometrically in size, but still contain the pointer the the next block rather than them being in a separate index block.

[1]:https://cs.uwaterloo.ca/research/tr/1999/09/CS-99-09.pdf

[2]:https://dl.acm.org/doi/10.5555/1756972.1756975

comment 3w ago · link · parent

Well, you can have certain differences of opinion as long as they're "acceptable" opinions. Academia ousts those who don't fit into its culture. Tenure is the only way you can express your real opinion without reprisal, though you may still be socially outcast for having the "wrong" opinion - and those who make it this far are predominantly products of that same culture - their opinions align with their peers on what is deemed acceptable. The anointed.

comment 3w ago · link · parent

You can take what you see here and extrapolate. HN is overwhelmingly "intellectuals" - many academics, though not all. We can see:

* Everyone is quick to make judgement on something they don't know all the details of.

* There's not much agreement - mostly people disagreeing with each other.

* Everyone's opinion is important - they're smart so obviously, they're always right.

* Unrelated politics - my pet issue must be talked about.

* Anything is better - it's impossible for things to get worse.

* I disagree with this opinion so it must be a Russian bot.

Anyway, I wonder what will happen if you get together a bunch of intellectuals in government.

comment 3w ago · link · parent

It's more the kind of deciding how to spend other people's money.

Both government and academia know how to navigate this well - by avoiding accountability.

comment 1mo ago · link · parent

I find it easier to think of them as transforms which turn "a function which accepts/returns plain values" into a "function which accepts and returns a type which embeds plain values".

    map     :: (a -> b)     -> (t a -> t b) -- Functor
    bind    :: (a -> t b)   -> (t a -> t b) -- Monad
    cobind  :: (t a -> b)   -> (t a -> t b) -- Comonad
    ap      :: t (a -> b)   -> (t a -> t b) -- Applicative
The resulting function type is the same in all these cases - the difference is the type of the input function. There are other similar functions which return a `(t a -> t b)` too.

The "ordered computation" isn't unique to monads, it applies to all of these when you chain them. For monads particularly though, you can't begin the continuation until the previous result has been generated - whereas with a comonad, you can begin the continuation right away and extract the value afterwards (inside the continuation).

Can also think of it like a producer/consumer or push/pull thing. Monads push values into some type `t`, and comonads pull values out of `t`.

The naming of `return` is perhaps unfortunate as it gives the impression you're returning a value (done to make do-notation look like imperative code) - but monads don't return values. `return` produces a computation.

`coreturn` is usually called `extract`, which is better naming - it extracts a value from a computation.

The order of arguments is also unfortunate because it makes the above pattern less obvious - they're usually written as:

    fmap :: f a -> (a -> b) -> f b
    bind :: m a -> (a -> m b) -> m b
So it's not obvious that `fmap` is transforming a function `(a -> b)` into one `(f a -> f b)`, etc.

comment 1mo ago · link · parent

It's not learning. The description says it does a maximal munch, which is obviously going to be wrong a lot of the time.

Should probably use MeCab, which parses this correctly.

comment 1mo ago · link · parent

There's also function composition

   (h . g . f) x
Or for LtR, with Control.Category

   (f >>> g >>> h) x
Could combine with the forward pipe for

   x |> (f >>> g >>> h)

comment 1mo ago · link · parent

  typedef struct {
      double value;
      int    error;
  } maybe_double;
Is most efficient on x86-64 SYSV, because the ABI supports the `error` being returned in a GP register, and the `value` in a vector register. The struct is returned in `rax:xmm0` - the double is where it is meant to be.

When you use a union containing an int and a double, the double has to be moved to a GP register, and back to the vector register when read as a double (via movq), so there's a small hidden cost compared to the former approach. Your `Result_double` is returned in `rax:rdx`.

There's a trick you can use to avoid this - keep the `double` in the vector register and move the `int` to the vector register instead - so you only pay the cost to move between GP and vector registers when there's an error but not otherwise. To do this, make the union use `__m64` instead of `int` - the whole union is then in a vector register, and the `Result_double` struct is returned in `rax:xmm0`, as with `maybe_double` struct.

   typedef struct {
        _Bool ok;
        union {
            double value;
            __m64 error;
        };
    } Result_double;
Of course, this is x86-64 SYSV only. On AARCH64, the double will always be moved to a GP register in either example. Other conventions may also differ - MSVC in particular is poor because it converts to pass-by-pointer to a stack allocated structure for any struct greater than 64-bits.

On MSVC we could maybe get maximum efficiency by using NaN-boxing - store the error code in the signalling NaN space - eg, treat NaNs beginning 0x7FF1 as error codes.

   typedef union {
       int64_t _as_int;
       double _as_double;
   } Result_double;
   
   #define Result_double_value(n) \
       (Result_double){ ._as_double = (n) };
   #define Result_double_error(errcode) \ 
       (Result_double){ ._as_int = (0x7FF1000000000000ULL | (errcode)) }
   #define Result_double_is_error(x) \
       (((x)._as_int & 0x7FFF000000000000ULL) == 0x7FF1000000000000ULL)
   #define Result_double_get_error(x) \
       ((x)._as_int & 0x0000FFFFFFFFFFFFULL)
   #define Result_double_get_value(x) \
       ((x)._as_double)

   Result_double x = strtod·or·error(s, NULL)
   if (Result_double_is_error(x)) {
      handle(Result_double_get_error(x));
      return;
   }
   use(Result_double_get_value(x))
The `Result_double` then gets returned in `rax` and avoids touching the stack. Could probably improve this to return in `xmm0` instead.

comment 1mo ago · link · parent

Returning 2 values can be more performant than returning one and assigning to another as an "out parameter".

Eg:

    typedef struct {
        bool has_value;
        int value;
    } option_int_t;

    option_int_t foo() {
        if (somecond) return (option_int_t){ true, somevalue };
        else return (option_int_t){ false };
    }
  
    bool bar(int *out) {
        if (somecond) {
            *out = somevalue;
            return true;
        }
        return false;
    }
`foo` is slightly more efficient than `bar` on 64-bit SYSV, whose ABI supports 128-bit ("two eightbytes") returns in hardware registers. `bar` requires at least one dereference to assign the result.

On other compilers this isn't the case. MSVC only supports 64-bit returns and would use the stack for `option_int_t`. The caller allocates the space and an implicit pointer is passed in the first argument register (eg, `rcx`), and the same pointer is returned as the result.

comment 1mo ago · link · parent

Sum types in the set theoretic approach can be made with `(A & ¬B) | (¬A & B)`, or equivalently `(A | B) & (¬A | ¬B)`.

There's no mainstream language with negation types, but a few good research languages with them, eg MLstruct.

[MLstruct]:https://github.com/hkust-taco/mlstruct

12345
56