【发布时间】:2012-01-12 18:40:41
【问题描述】:
我想编写一个生成字符串的函数。该字符串仅包含 1,0,s 和 S。 数字是二进制数。每个数字通过 s 分隔。一个数字给出了字符串其余部分的长度。大写的 S 是字符串的结尾。
例子:
func :: Integral a => a -> String
func 1
"1S"
func 3
"110s11s1S"
func 4
"1010s110s11s1S"
我的问题是,我不知道如何获得尾巴的长度("s1S" -> tail、11 -> head)而不是获得新的尾巴。
我的新代码:
>toBinary :: Integral a => a -> String
>toBinary 0 = []
>toBinary x
> | mod x 2 == 0 = '0' : toBinary (div x 2)
> | mod x 2 == 1 = '1' : toBinary (div x 2)
>zubinaer :: Integral a => a -> String
>zubinaer x = reverse (toBinary x)
>
>distan :: Integral a => a -> String
>distan n = if n > 0 then hilfsfunktion (n-1) "1S" else []
>
> where
> hilfsfunktion :: Integral a => a -> String -> String
> hilfsfunktion 0 s = s
> hilfsfunktion n s = hilfsfunktion (n-1) (zubinaer(length s + 1) ++ "s" ++ s )
这是我的旧代码:http://hpaste.org/54863
【问题讨论】:
-
是的。所以我想我可以得到一些提示。感谢您的帮助。 :)
-
@Alexei 该代码对初学者来说还不错。尝试使用地图!它确实可以节省您的工作量。
标签: haskell