Alexei
Alexei

Reputation: 347

function that generates a String in Haskell

I want to program a function that generates a String. The String contains only 1,0,s and S. The numbers are binary numbers. Each number is separated through a s. And a number gives the length of the rest of the String. The capital S is the end of the String.

Examples:

func :: Integral a => a -> String

func 1

"1S"

func 3

"110s11s1S"

func 4

"1010s110s11s1S"

My problem is, that I don't know, how I can get the length of the tail ("s1S" -> tail, 11 -> head) and than get the new tail.

My new code:

>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 )

Here my older code: http://hpaste.org/54863

Upvotes: 3

Views: 197

Answers (2)

hugomg
hugomg

Reputation: 69924

Since the tail is defined recursively (ex.: the "tail" of (f 4) is (f 3)) you can get the length of the tail by first getting the tail:

let the_tail = f (n-1) in

then calling the length function on it

length the_tail

Upvotes: 0

fuz
fuz

Reputation: 92966

I think you are tackling your problem from the wrong angle. In Haskell, one often thinks of lists. Actually, a String is just a list of Chars. Try to build your function from these bricks:

  • Write a function toBinary :: Integral a => a -> [Bool] that outputs a binary representation of its parameters. A 1 is True and a 0 is False
  • You can use map to turn the [Bool] into a String by replacing each boolean by a character 0 or 1.
  • You can use the syntax [1..n] to generate a list of integers from 1 to n. Use map to generate a list of binary representation strings.
  • Use intercalate from Data.List to create your string.

Upvotes: 2

Related Questions