我是Haskell的新手,但有一些ActionScript 3.0面向对象的经验。因此正在进行一次重大的编程转变。我已经阅读了关于Haskel的基础知识,例如算术。我可以编写简单函数。
作为一个实际的任务,我需要在Haskell中使用计算机生成Thue-Morse sequence(称为tms1)。应该像这样:
但是这段代码并没有得到期望的结果。非常感谢任何帮助。
作为一个实际的任务,我需要在Haskell中使用计算机生成Thue-Morse sequence(称为tms1)。应该像这样:
>tms1 0
0
>tms1 1
1
>tms1 2
10
>tms1 3
1001
>tms1 4
10010110
等等……根据维基百科,我应该使用公式。
t0 = 0
t2n = tn
t2n + 1 = 1 − tn
我不知道如何在Haskell中实现这个公式。你能指导我创建一个吗? 这是我目前得到的:
module ThueMorse where
tms1 :: Int -> Int
tms1 0 = 0
tms1 1 = 1
tms1 2 = 10
tms1 3 = 1001
tms1 x = tms1 ((x-1)) --if x = 4 the output will be 1001, i don't know how to make this in a recursion function
我在互联网上做了一些研究,找到了这段代码。
Source: http://pastebin.com/Humyf6Kp
代码:
module ThueMorse where
tms1 :: [Int]
tms1 = buildtms1 [0] 1
where buildtms1 x n
|(n `rem` 2 == 0) = buildtms1 (x++[(x !! (n `div` 2))]) (n+1)
|(n `rem` 2 == 1) = buildtms1 (x++[1- (x !! ((n-1) `div` 2))]) (n+1)
custinv [] = []
custinv x = (1-head x):(custinv (tail x))
tms3 :: [Int]
tms3 = buildtms3 [0] 1
where buildtms3 x n = buildtms3 (x++(custinv x)) (n*2)
intToBinary :: Int -> [Bool]
intToBinary n | (n==0) = []
| (n `rem` 2 ==0) = intToBinary (n `div` 2) ++ [False]
| (n `rem` 2 ==1) = intToBinary (n `div` 2) ++ [True]
amountTrue :: [Bool] -> Int
amountTrue [] = 0
amountTrue (x:xs) | (x==True) = 1+amountTrue(xs)
| (x==False) = amountTrue(xs)
tms4 :: [Int]
tms4= buildtms4 0
where buildtms4 n
|(amountTrue (intToBinary n) `rem` 2 ==0) = 0:(buildtms4 (n+1))
|(amountTrue (intToBinary n) `rem` 2 ==1) = 1:(buildtms4 (n+1))
但是这段代码并没有得到期望的结果。非常感谢任何帮助。
a \
rem` 2 == 0/
1写成
even a和
odd a。
custinv x可以定义为
map (\a -> 1-a) x,甚至可以简化为
custinv = map (1-)。
amountTrue x = sum (fromEnum x)或者
amountTrue x = length (filter id x)`。 - sdcvvc