Comment detail

2進数の記述 (Nested Flatten)
1
2
3
4
5
bin :: [Integer] -> Integer
bin = foldl (\x y -> x * 2 + y) 0

-- Prelude> bin[0, 1, 1, 0, 1, 0, 0, 1]
-- 105

リストで書くのはめんどくさいので。

1
2
3
4
5
6
b :: Integer -> Integer
b 0 = 0
b x = b' x + 2 * b (div x 10)
    where b' x = if odd x then 1 else 0

main = print $ b 01101001  -- 10

Template Haskell を使ってみた。 2ファイルあります。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{- binmain.hs -}

import Bin

main = print $(b 01101001)



{- bin.hs -}

module Bin (b) where

import Language.Haskell.TH

bin :: Integer -> Integer
bin 0 = 0
bin x = bin' x + 2 * bin (div x 10)
    where bin' x = if odd x then 1 else 0

b x = litE $ IntegerL $ bin x

{-
>> ghc --make -fth binmain.hs 
>> ./binmain
105
-

Index

Feed

Other

Link

Pathtraq

loading...