开发者

Haskell. Numbers in binary numbers. words

import Data.Char


blockCode :: S   

lett2num :: Char ->  Int
lett2num y 
   | (or


num2bin :: Int -> [Int]
num2bin n: negative number"
  where n2b 0  =  []
        n2b n  =  n `mo开发者_如何转开发d` 2 : n2b (n `div` 2)


You can use concatMap show to transform a list into a string:

Main> num2bin 8
[0,0,0,1]
Main> concatMap show $ num2bin 8
"0001"

but note that your function's output is reversed.

To do everything in one go, do

num2bin :: Int -> String
num2bin n
  | n >= 0     =  concatMap show $ reverse $ n2b n
  | otherwise  =  error "num2bin: negative number"
  where n2b 0  =  []
        n2b n  =  n `mod` 2 : n2b (n `div` 2)


Function converts integer to binary:

num2bin :: (Integral a, Show a) => a -> String
num2bin 0 = "0"
num2bin 1 = "1"
num2bin n
    | n < 0         = error "Negative number"
    | otherwise     = num2bin (n `div` 2) ++ show (n `mod` 2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜