【问题标题】:Convert to binary notation in Haskell在 Haskell 中转换为二进制表示法
【发布时间】:2021-06-06 14:34:37
【问题描述】:
有没有更好的方法来检查这段代码中的n 和c,也许是模式匹配或者更类似于 Haskell 的东西?
toBin :: Int -> Int -> [Int]
toBin n c
| n < 0 = []
| c <= 0 = []
toBin n c = toBin (n `div` 2) (c - 1) ++ [n `mod` 2]
【问题讨论】:
标签:
haskell
binary
pattern-matching
data-conversion
idioms
【解决方案1】:
这里最好使用累加器,这样可以防止 O(n) 追加导致 O(n2) 代码中的算法:
toBin :: Int -> Int -> [Int]
toBin = go []
where go rs n c
| n < 0 || c <= 0 = rs
| otherwise = go (r:rs) q (c-1)
where (q,r) = quotRem n 2
因此,我们在这里从一个空列表开始,每次都在列表前面加上下一个余数,直到数字为零或位数为 0。
【解决方案2】:
嗯,它们都是布尔表达式,所以你可以将它们与||结合起来
toBin n c | n < 0 || c <= 0 = []