News for hackers. Stuff that matters.
Re:Show HN: Verify JSON using minimal schema by ken on Thursday April 16, 2020 @10:23AM (#22889652)
What statically typed language lets me define a type as “number between -180 and +180”, or “string which contains only alphanumeric chars”?

I think that would be a great feature but from what I see static typing fails here, too.

Re:Show HN: Verify JSON using minimal schema by rraval on Thursday April 16, 2020 @11:45AM (#22890565)
> What statically typed language lets me define a type as “number between -180 and +180”, or “string which contains only alphanumeric chars”?

Pretty much all of them. Any simple predicate like this can be encoded with witness types.

Here's an example in Java, which is hardly the paragon of static typing (i.e. it's no Haskell/Idris/Agda/Rust/Typescript):

    class AlphaNumericString {
        private final String str;

        // use a fallible factory with a `private` constructor if you're
        // morally opposed to exceptions
        public AlphaNumericString(String str) throws AlphaNumericException {
            if (!str.matches("^[a-zA-Z0-9]*$")) {
                throw new AlphaNumericException();
            }

            this.str = str;
        }

        private static class AlphaNumericException extends Exception {
        }
    }
Now code can freely use `AlphaNumericString` and be guaranteed that it has been validated.

You may object and say that newtype wrapping is cumbersome but:

1. That's an argument about sugar and ergonomics, not about the semantics that the static type system enforces

2. Some languages make it easier to generate forwarding methods to the underlying type (a la https://kotlinlang.org/docs/reference/delegation.html)

3. The `AlphaNumericString` is describing a smaller set of values than `String`. In general, you should be strongly considering the methods you allow and make sure that all paths continue to enforce the semantics you intend.

Re:Show HN: Verify JSON using minimal schema by wry_discontent on Thursday April 16, 2020 @11:04AM (#22890112)
It's not statically typed, but you can do this with clojure.spec

  (s/def ::number #(<= -180 % 180))
  (s/def ::my-string (s/and string? #(re-matches #"[a-zA-Z0-9]*" %)))
Re:Show HN: Verify JSON using minimal schema by metalrain on Thursday April 16, 2020 @11:21AM (#22890302)
I think Idris does, see http://docs.idris-lang.org/en/latest/tutorial/typesfuns.html... But probably there is some horrible trade-off or limits that seem arbitrary.
Re:Show HN: Verify JSON using minimal schema by arethuza on Thursday April 16, 2020 @11:19AM (#22890271)
I think Pascal's subranges would cover both those examples?

NB Last time I used Pascal was probably 35 years ago....

Edit: I would suspect Ada would have something like this.

Re:Show HN: Verify JSON using minimal schema by JoeAltmaier on Thursday April 16, 2020 @10:26AM (#22889683)
Been missing this for 20 years.