Search code examples
haskellbinarypattern-matchingdata-conversionidioms

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]

Solution

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

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