Webel
Webel

Reputation: 15

Replace a pattern of elemts in a list Haskell

(I'm a complete newbie to stackoverflow, will do my best to ask my question appropiatly, feel free to probe me if I don't).

So, I'm new to Haskell and I'm doing some exercises to get the hang of it.

I've solved half of a exercise which is to replace every occurance of a consonant in a string with that consonant + 'o' + that consonant, then return the new string, here's the code:

hurdyGurdy c = concat [ if n `elem` "AEOUYaeouy" then [n] else [n, 'o', n] | n <- c]

Although I'm completely stuck at turning hurdyGurdy string back into it's corresponding normal word, ie "HoHelollolo" should become "Hello".

So I'm thinking that I know that every consonant will have a next character 'o', and if I can just delete/drop these out of the list, it's all hunky dory. Or if I replace the whole [n, 'o', n] with n. Although I just don't know how to go about this.

I'm guessing the first way would be simplest, but how do I get rid of the current element AND the next one?

This isn't exactly homework, it's warm up to homework..!

Edit: I've solved it like this.. not exactly nice to look at thou

unRovarsprak ("") = ("")
unRovarsprak (c1:'o':c2:xs)
       | isConsonant c1 = c1 : unRovarsprak xs
   | otherwise   = xs
unRovarsprak (c1:xs) 
   | c1 `elem` vokaler = c1 : unRovarsprak xs
   | otherwise      = xs

Upvotes: 0

Views: 343

Answers (1)

JB.
JB.

Reputation: 42134

You'll probably want to use a basis of the sort:

unHurdyGurdy (c1:'o':c2:xs)
  | isConsonnant c1 && c2 == c1 = c1 : unHurdyGurdy xs

This leaves as an exercise for the reader:

  • writing isConsonnant
  • handling vowels
  • handling pattern matching failures (strings that aren't the result of hurdyGurdy)

Upvotes: 2

Related Questions