Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

Removing prepending “0” output from Haskell toBinary function that converts number to binary string?

I am new to Haskell. My function is supposed to take an integer and convert it to a string in base 2. My code works correctly, but I would like to remove "0" from my results.

For example, toBinary 16 outputs "010000" rather than "10000", as I would like.

Does anyone have any advice?

toBinary :: Integer -> [Char]

toBinary x = if (x == 0) then "0" else toBinary ( div x 2 ) ++ show(mod x 2 )
question from:https://stackoverflow.com/questions/65906539/removing-prepending-0-output-from-haskell-tobinary-function-that-converts-numb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need a helper function that calls your recursive function, as there's only one case in which you want to prepend "0" (when the number is 0).

toBinary' :: Integer -> String
toBinary' 0 = ""
toBinary' x = toBinary' (div x 2) ++ show (mod x 2)

toBinary :: Integer -> String
toBinary 0 = "0"
toBinary x = toBinary' x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...