Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General-purpose language to specify value constraints

I am looking for a general-purpose way of defining textual expressions which allow a value to be validated.

For example, I have a value which should only be set to 1, 2, 3, 10, 11, or 12. Its constraint might be defined as: (value >= 1 && value <= 3) || (value >= 10 && value <= 12)

Or another value which can be 1, 3, 5, 7, 9 etc... would have a constraint like value % 2 == 1 or IsOdd(value).

(To help the user correct invalid values, I'd like to show the constraint - so something descriptive like IsOdd is preferable.)

These constraints would be evaluated both on client-side (after user input) and server-side. Therefore a multi-platform solution would be ideal (specifically Win C#/Linux C++).

Is there an existing language/project which allows evaluation or parsing of similar simple expressions?

If not, where might I start creating my own?

I realise this question is somewhat vague as I am not entirely sure what I am after. Searching turned up no results, so even some terms as a starting point would be helpful. I can then update/tag the question accordingly.

like image 882
g t Avatar asked Dec 18 '13 09:12

g t


2 Answers

You may want to investigate dependently typed languages like Idris or Agda.

The type system of such languages allows encoding of value constraints in types. Programs that cannot guarantee the constraints will simply not compile. The usual example is that of matrix multiplication, where the dimensions must match. But this is so to speak the "hello world" of dependently typed languages, the type system can do much more for you.

like image 191
Ingo Avatar answered Sep 19 '22 06:09

Ingo


If you end up starting your own language I'd try to stay implementation-independent as long as possible. Look for the formal expression grammars of a suitable programming language (e.g. C) and add special keywords/functions as required. Once you have a formal definition of your language, implement a parser using your favourite parser generator.

That way, even if your parser is not portable to a certain platform you at least have a formal standard from where to start a separate parser implementation.

like image 34
Florian Brucker Avatar answered Sep 20 '22 06:09

Florian Brucker