praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Next.hs (427B)


      1 {-# OPTIONS_GHC -Wall #-}
      2 
      3 import Data.Bits ((.&.))
      4 import Data.Function (fix)
      5 
      6 hweight :: Int -> Int
      7 hweight m =
      8   let loop r acc j
      9         | j == 0    = acc
     10         | otherwise = r (succ acc) (j .&. pred j)
     11 
     12   in  fix loop 0 m
     13 
     14 next :: Int -> Int
     15 next m =
     16   let hw = hweight m
     17 
     18       loop r n
     19         | hweight n == hw = n
     20         | otherwise       = r (succ n)
     21 
     22   in  fix loop (succ m)
     23 
     24 main :: IO ()
     25 main = print (next 7)
     26