by Sandman · 6y ago · 0 comments
EDIT: Some of you asked what about languages that don't support such more constrained types, so to answer all of you here: different languages have different capabilities, of course, so while some may make what I proposed trivial, in others it would be almost or literally impossible. However, I believe most of the more popular languages support creation of custom data types? So the idea (for those languages at least) is quite simple - hold the value as a float, but wrap it in a custom data type that makes sure the value stays within bounds through accessor methods.
Fortunately, my preferred programming language, Raku, makes creating this sort of subset trivially easy[0]:
subset UnitInterval of Real where 0 ≤ * ≤ 1
[0]: https://docs.raku.org/language/typesystem#index-entry-subset...Say you need to represent velocity in a transportation simulation. You could have a function, velocity, that looks like this:
double velocity(double v, char * of_what)
You use it to wrap constrained values. E.g., double v_jogger = velocity(8.0, "human");
double v_car = velocity(65.0, "city car");
velocity() simply returns the first argument, after doing validity checking based on the second argument.You probably couldn't reasonably use this everywhere that you would use actual constrained types in a language that has them, but you could probably catch a lot of errors just using them in initializers.
@Clamping(0...14) var pH: Double = 7.0
https://nshipster.com/propertywrapper/#implementing-a-value-...This got me thinking: What about a situation where the accuracy is given in a real-life unit. For example, the accuracy of a GPS measurement, given in meters. I've sometimes used names like 'accuracyInMeters' to represent this, but it felt a bit cumbersome.
Edit: Thinking more about it, I guess you could typealias Float to Meters, or something like that, but also feels weird to me.
Another thing you can do is define a "METER" constant equal to 1. You can then call your function like this: func(1.5 * METER), and when you need a number of meters, you can do "accuracy / METER". The multiplication and division should be optimized away.
Good thing about that is that you can specify the units you want, for example you can set FOOT to 0.3048 and do "5. * FOOT" and get back your result in centimeters by doing "accuracy / CENTIMETER". The last conversion is not free if the internal representation is in meter but at least, you can do it and it is readable.
If you are going to use such distances a lot, at least in C++, you can get a bit of help from the type system. Define a "distance" class operator overloads, constants and convenience functions to enforce consistent units. Again, the optimizer should make it not more costly than using raw floats if that's what you decide to use as an internal representation.
The newtype wrapper doesn't show up at runtime, only at compile time. It can be set up in such a way that the compiler complains about adding GpsInMeters to GpsInMiles naively.
You'd be surprised where the support is. In C#, you would declare a struct type with one read only field of type double, and range validation (x <= x <= 1) in the constructor.
this is the "value object" pattern. http://wiki.c2.com/?ValueObject
Yes there's a bit of boilerplate - especially since you might want to override equality, cast operators etc. But there is support. And with a struct, not much overhead to it.
"public Customer GetById(CustomerId id)" instead of "public Customer GetById(string id)" when only some strings (e.g. 64 chars A-Z and 1-9) are valid customer ids.
Compile-time validation would be ideal, but validation at the edges, well before that method, is good enough.
https://www.joelonsoftware.com/2005/05/11/making-wrong-code-...
Can float types even support 0, 1 inclusive? You just can't represent natural numbers like that with floats...
It seems disingenuous to me to suggest that anyone using other languages do not have this problem. And really, there are quite a few languages to not have this form of typing, and even some reasons for a language to not want this form of typing.
So please, don't answer a question by saying "your questions is wrong" it is condescending and unhelpful.
The point remains that the fact a given parameter's valid values are [0,1] is not a function of it's name. You can check the values within the method and enter various error states depending on the exact business rules.
"here is what seems like a better question" is helpful, especially in a discussion forum separate from the original Q/A.
But if "here is what seems like a better question" is the _only_ response or drowns out direct responses, then thats still frustrating.
> condescending
As a man who sometimes lacks knowledge about things, when I ask a question, please please please err on the side of condescending to me rather than staying silent. (No, I don't know how you should remember my preferences separately from the preferences of any other human)
I merely wanted to point out that, in my opinion, this property should be reflected in parameter type, rather than the name. Just like, if we wanted a parameter that should only be a whole number, we wouldn't declare it as a float and name it "MyVariableInteger" and hope that the callers would only send integers.
You mentioned that there are quite a few languages that do not permit what I proposed, would you mind specifying which ones exactly? The only one that comes to my mind is assembly?
To avoid that, you need to document that the value should be between 0 and 1, and you could do that with a comment line (which the OP wanted to avoid), or by naming the variable or type appropriately: And that takes us back to the original question. (Whether the concept is expressed in the parameter name or parameter type (and its name) is secondary.)
I'm not sure I understand this. See below, but the larger point here is that the type can never lie -- names can and often do because there's no checking on names.
I think what is being proposed is something similar to
newtype Accuracy = Accuracy Float
and then to have the only(!) way to construct such a value be a function mkAccuracy :: Float -> Maybe Accuracy
which does the range checking, failing if outside the allowable range.Any functions which needs this Accuracy parameter then just take a parameter of that type.
That way you a) only have to do the check at the 'edges' of your program (e.g. when reading config files or user input), and b) ensure that functions that take an Accuracy parameter never fail because of out-of-range values.
It's still a runtime-check, sure, but but having a strong type instead of just Float, you can ensure that you only need that checking at the I/O edges of your program and absolute assurance that any Accuracy handed to a function will always be in range.
You can do a similar thing in e.g. C with a struct, but unfortunately I don't think you can hide the definition such that it's impossible to build an accuracy_t without going through a "blessed" constructor function. I guess you could do something with a struct containing a void ptr where only the implementation translation unit knows the true type, but for such a "trivial" case it's a lot of overhead, both code-wise and because it would require heap allocations.
you have a very valid point but it would come across even more effectively without that part, i believe.
real<lower = 0, upper = 1> accuracy; function FuncName(UnitInterval accuracy) function FuncName(NormalizedFloat accuracy)
In languages with operator overloading you can make NormalizedFloat a proper class with asserts in debug version and change it to an alias of float in release version.Similarly I wonder why gemoetry libraries don't define separate Point class and Vector class, they almost always use Vector class for vectors and points.
I understand math checks out, and sometimes you want to add or multiply points, for example:
Pmid = (P0 + P1) / 2
But you could cast in such instances: Pmid = (P0 + (Vector)P1)/ 2
And the distinction would surely catch some errors. Point - Point = Vector
Point + Point = ERROR
Vector +/- Vector = Vector
Point +/- Vector = Point
Point * scalar = ERROR
Vector * scalar = Vector
Point */x Point = ERROR
Vector * Vector = scalar
Vector x Vector = VectorUnitIntervalNumber would be better, but it's too long. Something like UnitNumber or UnitFloat could maybe work.
I have actually used intervals, and should have realised this sooner. But I just had my first cup of coffee...
I wish I were commenting here with an answer, but I don't have one. "brightness01" is a common naming convention for values of this type in computer graphics programming, but niche enough that it got raised in review comments by another gameplay programmer.
This begs an interesting tangential question: Which programming languages allow such resticted intervals as types?
type percentage:=int[0,100] type hexdigit:=int[0,15] …
since this might be overkill, sane programming languages might encourage assert statements inside the functions.
-- A float between 0 and 1, inclusive.
type UnitInterval = Float
foo :: UnitInterval -> SomeResultPresumably
foo accuracy = ...
i.e. I think the essential problem in the SO question is solved, even though we have no additional type safety.A language without type synonyms could do just as well with CPP defines
You’d have to decorate/call manually in your functions so it’s not watertight, but at least it’s DRY.
I propose "pun" - proportion of unity, or "p(er) un".
I like verbosity!
Or use a dependent type language. Maybe Idris? Then something like Between(0,1) I guess.
So instead of
func call(Person person){} you just have func call(person){}
where person is a known type AND the variable name.
In that scenario 'accuracy' would be a type with known value between 0 and 1.
{person}
Is an object person with key person and value person of type Person
func call(person#1 person#2){}
function call(person#sender person#receiver)
And at that point we're back to the square one, just remove the # :)No, most don't, except if you go into building custom classes.
That seems a very elaborate way to say “No" when the answer is really “Yes”.
Or in other words, a succint way to say "Technically yes, but practically useless, so no".
-- BetweenZeroAndOne.elm
module BetweenZeroAndOne exposing (get, set)
type BetweenZeroAndOne = BetweenZeroAndOne Float
set : Float -> BetweenZeroAndOne set value = BetweenZeroAndOne (Basics.clamp 0.0 1.0 value)
get : BetweenZeroAndOne -> Float get (BetweenZeroAndOne value) = value
[0] https://en.wikipedia.org/wiki/Opaque_data_type#:~:text=In%20....
It's the same question of, how can you convert a string to a Regexp type if not all strings are valid Regexps?
> In other words, the parameter should not be a float, but a more constrained type that allows floats only in [0,1]
It's a value check, not a type check.
type NormalisedFloat = number
Admittedly it doesn't add any actual value checking, but it does convey the information when you look at the parameter definition.