satubus
satubus

Reputation: 27

haskell: binary calculator recursion and return values?

I wanted to change decimal numbers into binary numbers per recursion and if else!

binary2 x =
   if x > 0
       then binary x
       else 999

binary x =
    if x `mod` 2 > 0
      then 1 && binary2 (x/2)
      else 0 && binary2 (x/2)

well returning 0 or 1 in combination with boolean does not work, I want to return whether 0 or 1 and then referate again to the function but with half the value as before until x < 1! Therefore x/2...

Upvotes: 0

Views: 354

Answers (2)

hasufell
hasufell

Reputation: 573

Something like

binary2 :: Int -> [Int]
binary2 x
  | x > 0 = binary x
  | otherwise = []


binary :: Int -> [Int]
binary x
  | x `mod` 2 > 0 = binary2 (x `div` 2) ++ [1]
  | otherwise     = binary2 (x `div` 2) ++ [0]

So I'd just choose a list of Ints.

Upvotes: 1

Sebastian Redl
Sebastian Redl

Reputation: 71979

binary, decimal, hexadecimal etc. are representation systems for numbers. They only matter when you deal with strings containing numbers, not when you deal with numbers on the programming language level.

Upvotes: 0

Related Questions