commit 709bb1f9376992367d4b3527155d98d12e02bf58 parent b6fd14b8aefa12007aada8f3785a12018d5f940f Author: Jared Tobin <jared@jtobin.ca> Date: Sun, 24 Jun 2018 16:21:37 +1200 Add next identical popcount exercise. Diffstat:
A | 20180622_popcount/Next.hs | | | 26 | ++++++++++++++++++++++++++ |
1 file changed, 26 insertions(+), 0 deletions(-)
diff --git a/20180622_popcount/Next.hs b/20180622_popcount/Next.hs @@ -0,0 +1,26 @@ +{-# OPTIONS_GHC -Wall #-} + +import Data.Bits ((.&.)) +import Data.Function (fix) + +hweight :: Int -> Int +hweight m = + let loop r acc j + | j == 0 = acc + | otherwise = r (succ acc) (j .&. pred j) + + in fix loop 0 m + +next :: Int -> Int +next m = + let hw = hweight m + + loop r n + | hweight n == hw = n + | otherwise = r (succ n) + + in fix loop (succ m) + +main :: IO () +main = print (next 7) +