MarcoCabral Posted October 16, 2016 at 10:36 PM Report #599660 Posted October 16, 2016 at 10:36 PM Oi, eu sou novo programando em haskell e estou com problema em fazer a conversão de binário para decimal. Já consegui fazer de decimal para binário como podem ver abaixo: decpbin :: Int -> String decpbin 0 = "0" decpbin 1 = "1" decpbin n = decpbin(n `div` 2) ++ show(n `mod` 2) Se poderem ajudar agradeço.
jota.fullstack Posted October 18, 2016 at 02:37 PM Report #599689 Posted October 18, 2016 at 02:37 PM Uma solução rápida: fromBinary :: String -> Int fromBinary str = sum $ zipWith toDec (reverse str) [0 .. length str] where toDec a b = digitToInt a * (2 ^ b) Espero ter ajudado.
Baderous Posted November 3, 2016 at 11:22 AM Report #600101 Posted November 3, 2016 at 11:22 AM (edited) Em 18/10/2016 às 15:37, jota.fullstack disse: Uma solução rápida: fromBinary :: String -> Int fromBinary str = sum $ zipWith toDec (reverse str) [0 .. length str] where toDec a b = digitToInt a * (2 ^ b) Espero ter ajudado. Esta solução, para além de introduzir funções de ordem superior, que julgo já serem avançadas dado o exercício típico de iniciante em Haskell, não me parece nada rápida. Já viste quantas vezes estás a percorrer a string inicial? Penso que o que se pretende é algo mais básico e até mais rápido. Vou deixar aqui visto que já passaram 15 dias. bin2dec :: String -> Int bin2dec "" = 0 bin2dec s = let l = length s - 1 in bin2dec' s l bin2dec' :: String -> Int -> Int bin2dec' "" _ = 0 bin2dec' (x:xs) l = (toInt x)*(2^l) + bin2dec' xs (l-1) toInt :: Char -> Int toInt c = ord c - ord '0' Edited November 3, 2016 at 11:23 AM by Baderous
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now