[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: guile-question: 3/2 -> "1 1/2"
From: |
Thomas Morley |
Subject: |
Re: guile-question: 3/2 -> "1 1/2" |
Date: |
Wed, 12 Aug 2015 01:09:11 +0200 |
2015-08-11 10:57 GMT+02:00 Thomas Morley <address@hidden>:
> 2015-08-11 8:19 GMT+02:00 David Kastrup <address@hidden>:
> [...]
>>
>> Well, how about something like
>>
>> (define (integer-and-fraction nmbr)
>> (let* ((wh (truncate nmbr)) (rem (- nmbr wh)))
>> (if (or (zero? wh) (zero? rem)) (format #f "~s" nmbr)
>> (format #f "~s ~s" wh (abs rem)))))
>>
>> (display (integer-and-fraction (/ 1111 7)))
>>
>> Of course the disadvantage being that you cannot distinguish between one
>> and two numbers and cannot read the number back in easily.
>>
>> --
>> David Kastrup
>
> Will have a closer look later, I'm in a hurry.
>
> Many thanks,
> Harm
I've got another suggestion from Andrew Bernard (agreeing to make it public)
Here both:
%% In a .ly-file:
%% Andrew:
#(define (mixed-num x)
(let* ((n (numerator x))
(d (denominator x)))
(cons (truncate (/ n d)) (/ (modulo n d) d))))
%% David:
#(define (integer-and-fraction nmbr)
(let* ((wh (truncate nmbr))
(rem (- nmbr wh)))
(if (or (zero? wh) (zero? rem))
(format #f "~s" nmbr)
(format #f "~s ~s" wh (abs rem)))))
#(write-me "mixed-num:\n"
(map mixed-num (iota 40 0 (/ 5 7))))
#(write-me "integer-and-fraction:\n"
(map integer-and-fraction (iota 40 -1 (/ 5 7))))
Some thoughts for the record:
Ofcourse the two suggestions return different type of output, pairs or strings.
(Wouldn't be too hard to let return both strings or pairs or whatever, though.)
`mixed-num' can't deal with negative input right now, returning wrong
(could be fixed ofcourse).
In case the input is not exact `mixed-num' crashes, whereas
`integer-and-fraction' doesn't, although returning not a fraction.
I think I'll go for `integer-and-fraction' and add an `exact?'-condition.
Thanks tons both,
Harm