Predicate for a string representing an integer

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Predicate for a string representing an integer

Urs Liska
Hi all,

I've found this function in my code:

% Returns true if obj is a string representation of an integer
#(define (integer-string? obj)
   (integer? (string->number obj)))

and I have the impression there should be a better way with more
built-in functionality to do it.

Any suggestions, or should I simply leave it at that?

Urs


--
[hidden email]
https://openlilylib.org
http://lilypondblog.org


_______________________________________________
lilypond-user mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/lilypond-user
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Predicate for a string representing an integer

Jan-Peter Voigt
Hi Urs,

the functions used are built-in so I'd probably also do it (almost) that
way. But I'd strongly recommend to test if obj is a string first:

#(define (integer-string? obj)
    (and (string? obj)(integer? (string->number obj))))

Otherwise the predicate fails with an error (not false) if the argument
is something else ... for example an integer.
I doubt that checking all characters in the string are in the range
'0'-'9' is faster then string->number.

Jan-Peter

Am 30.05.2017 um 10:47 schrieb Urs Liska:

> Hi all,
>
> I've found this function in my code:
>
> % Returns true if obj is a string representation of an integer
> #(define (integer-string? obj)
>     (integer? (string->number obj)))
>
> and I have the impression there should be a better way with more
> built-in functionality to do it.
>
> Any suggestions, or should I simply leave it at that?
>
> Urs
>
>


_______________________________________________
lilypond-user mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/lilypond-user
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Predicate for a string representing an integer

caagr98
On 05/30/17 11:13, Jan-Peter Voigt wrote:
> I doubt that checking all characters in the string are in the range
> '0'-'9' is faster then string->number.

Don't forget the optional leading hyphen, base specifiers (#x, #o, #d,
#b), etc.

However, do keep in mind that (integer? (string->number x)) accepts
"2/2", "1.0", "1e10", and even "1.0000000000000001" as integers, which
might not be what you want.

_______________________________________________
lilypond-user mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/lilypond-user
Loading...