[Nix-dev] isFloat

Harald van Dijk harald at gigawatt.nl
Tue Dec 29 21:38:01 CET 2015


On 29/12/2015 13:20, Игорь Пашев wrote:
 > Is anybody needs floats in options :-)
 >
 >    isFloat = x: isInt x ||
 >        ( isString x &&
 >          3 > length (splitString "." x) &&
 >          all (s: 2 == length (splitString s " 0123456789. "))
 > (stringToCharacters x)
 >        );

Nice. Here are some corner cases to consider though :)

   isFloat (sub 0 1) -> true
yet
   isFloat (toString (sub 0 1)) -> false

   isFloat "" -> true
   isFloat ".." -> true
   isFloat "1.2." -> true
   isFloat "1 2" -> true

How about this alternative using a regex?

   isFloat = x: with builtins;
     match "-?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)" (toString x) != null;

This assumes "1" is valid, "1.1" is valid, "1." is valid, ".1" is valid, 
but plain "." is invalid. It allows an optional leading minus sign 
regardless of whether the argument is an integer or a string. It doesn't 
allow any spaces, not even leading or trailing spaces.

If the precise syntax of allowable floating point numbers changes, for 
instance if "." must always be followed by a digit, if a leading "+" is 
also allowed, if exponential notation ("1E10") is supposed to be 
allowed, if some spaces should be allowed, etc., it can be tweaked 
fairly easily.

Cheers,
Harald van Dijk


More information about the nix-dev mailing list