Jump to content

Haskell Help

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Neoya

Neoya

    Newbie

  • Members
  • Pip
  • 2 posts
Hia

I have a problem that I can't solve, I have a function called 'shorten'
shorten :: [(Char,Int)] -> String

shorten as = concat(map shorten' as)

shorten' :: (Char,Int) -> String

shorten' (x,n) = [x,intToDigit n]

which produces the output
> shorten [('a'; 5); ('b'; 4); ('c'; 2)]
"a5b4c2"

but I need to make a function is essentially the inverse function of shorten called expand.

expand :: String -> [(Char; Int)]
that produces the following output

> expand "a5b4c2"
[('a'; 5); ('b'; 4); ('c'; 2)]
> expand "d9d3"
[('d'; 9); ('d'; 3)]

and I can't figure it out. I would appreciate any help as this is my last question.

with regards, Neoya

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
shorten :: [(Char,Int)] -> String

shorten as = concat(map shorten' as)
Nice, but use concatMap here. :)
shorten :: [(Char, Int)] -> String

shorten = concatMap shorten'
As far as expand goes, I'd try something like this, using pattern matching:
expand :: String -> [(Char, Int)]

expand [] = []

expand [x] = error "Last element missing int value."

expand (x:y:rs) = (x, read y :: Int) : expand rs
That's not tested, but I think it'll work. It's possible for read to fail, there's really no error checking. Just trying to put you on the right track.
Wow I changed my sig!

#3
Neoya

Neoya

    Newbie

  • Members
  • Pip
  • 2 posts
Thank you

I am just getting to grips with Haskell but that was a big help, I couldn't wrap my head around what needed to be done. I never thought to use ConCat Map, thats very useful.

The code works perfectly, thanks




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users