Haskell. Numbers in binary numbers. words

一世执手 提交于 2020-01-07 08:23:41

问题


import Data.Char


blockCode :: S   

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


num2bin :: Int -> [Int]
num2bin n: negative number"
  where n2b 0  =  []
        n2b n  =  n `mod` 2 : n2b (n `div` 2)

回答1:


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)



回答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)


来源:https://stackoverflow.com/questions/4682705/haskell-numbers-in-binary-numbers-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!