[Haskell-cafe] Rational and % operator remix

michael rice nowgate at yahoo.com
Sun Mar 29 16:12:59 EDT 2009


Correct, if it can be stated as a Rational then it terminates. I was messing around last night with the first function on a sequence that approximates sqrt(2)

cf (take 25 (1: [2,2..]))

forgetting that while the sequence is infinite, I only grabbed the first 25 elements.

Your replacement code works fine except for a missing

import Data.Ratio

It's quite removed from what I was trying so I'm going to have to read ahead a bit to understand it.

Thanks,

Michael


--- On Sun, 3/29/09, Daniel Fischer <daniel.is.fischer at web.de> wrote:

From: Daniel Fischer <daniel.is.fischer at web.de>
Subject: Re: [Haskell-cafe] Rational and % operator remix
To: haskell-cafe at haskell.org
Cc: "michael rice" <nowgate at yahoo.com>
Date: Sunday, March 29, 2009, 2:35 PM


-----Inline Attachment Follows-----

Am Sonntag 29 März 2009 19:40:19 schrieb michael rice:
> Hi,
>
> Thanks again for the help last night.
>
> The second function cf2 is an attempt to reverse the process of the 
first
> function, i.e., given a rational number it returns a list of integers,
> possibly infinite, 

Not for rational numbers.

> but you shouldn't get into trouble if you use 98%67 as
> input (output should be [1,2,6,5]). The interpreter is complaining 
about
> the '=' following the 'in' keyword. 

That should be '=='.

> Is there a better way to state this?
>
> Michael
>
> import Data.Ratio
> cf :: [Int] -> Rational
> cf (x:[]) = toRational x
> cf (x:xs) = toRational x + 1 / cf xs
>
> cf2 :: Rational -> [Int]
> cf2 a = let ai = toRational (floor ((numerator a) / (denominator a)))
>             in
>               if a = ai
>                 then [a]
>                 else ai : cf2 ((toRational 1) / (subtract ai a))

import Data.List (unfoldr)

cf3 :: Rational -> [Integer] -- Int may overflow
cf3 0 = [0]
cf3 x = a0:unfoldr f r
  where
    a0 = floor x
    r = x - fromInteger a0
    f 0 = Nothing
    f y = Just (properFraction $ recip y)





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090329/16aec78b/attachment.htm


More information about the Haskell-Cafe mailing list