如何生成循环的位串?

时间:2016-01-23 13:36:31

标签: algorithm haskell

请注意以下代码:

data Tree a = Node (Tree a) (Tree a) | Leaf a deriving Show

foldTree node leaf tree = go tree where
    go (Node a b) = node (go a) (go b)
    go (Leaf x)   = leaf x

toList :: Tree a -> [a] 
toList = foldTree (++) (\a->[a])

genTree a b c d e = iterate grow base where
    base          = e
    grow tree     = Node left right where
        left      = foldTree a c tree
        right     = foldTree b d tree

bins, grays :: [Tree String]
bins  = genTree Node Node        (Leaf.('0':)) (Leaf.('1':)) (Leaf [])
grays = genTree Node (flip Node) (Leaf.('0':)) (Leaf.('1':)) (Leaf [])

main = mapM 
    (\ (a, b) -> putStrLn (a ++ " " ++ b)) 
    (zip (toList (bins !! 3)) (toList (grays !! 3)))

该程序输出以下内容:

000 000
001 001
010 011
011 010
100 110
101 111
110 101
111 100

现在,让我们进行以下实验:我们转到一个随机行,在左边打印字符串,转到右边的字符串开头,重复。如果我们从100 110开始,我们将打印以下内容:100, 110, 101, 111, 100, 110, 101, 111, 100 ...。这无限地重复相同的4个数字。如果我们从第一行开始,我们将永远打印000我的问题是:我们是否可以用一个函数替换grays,以便在进行上述实验时,我们总是遍历所有行?

0 个答案:

没有答案