Jonathan Layduhur
Jonathan Layduhur

Reputation: 93

Convert to binary notation in Haskell

Is there a better way to check n and c in this code, maybe with pattern matching or something more Haskell-like?

toBin :: Int -> Int -> [Int]
toBin n c
    | n < 0 = []
    | c <= 0 = []
toBin n c = toBin (n `div` 2) (c - 1) ++ [n `mod` 2]

Upvotes: 1

Views: 120

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

It is better here to work with an accumulator, which prevents making O(n) appends that result in an O(n2) algorithm in your code:

toBin :: Int -> Int -> [Int]
toBin = go []
  where go rs n c
          | n < 0 || c <= 0 = rs
          | otherwise = go (r:rs) q (c-1)
          where (q,r) = quotRem n 2

We here thus start with an empty list, and each time prepend the list with the next remainder until the number is zero, or the number of bits is 0.

Upvotes: 0

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

Well, they're both boolean expressions, so you can combine them with ||

toBin n c | n < 0 || c <= 0 = []

Upvotes: 3

Related Questions