0
goal2 s = newstring s
where
newstring [] = []
newstring (h : m : t)
  | h == ' ' && m /= ' ' = m : newstring t
  | h /= ' ' && m == ' ' = newstring t
  | m == ' '             = newstring t
  | otherwise            = newstring t
  • Ok, one module loaded.

  • ghci> goal2 " apple pen pen pen" "appp"

  • ghci> goal2 " pen pineaple appen pen" "pp*** Exception: assign1_task1.hs:(103,5)-(108,42): Non-exhaustive patterns in function newstring

  • ghci> goal2 " pen pineapple apple pen" "ppap"

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Ethan Lim
  • 73
  • 7

2 Answers2

1
goal2 s = newstring s
 where
   newstring [] = []
   newstring [h] = []
   newstring (h : t)
   | h == ' '             =  head t : newstring t
   | otherwise            =  newstring t

Thanks once again dude.@Willem Van Onsem

  • ghci> goal2 " pen pine apple pen" "ppap"
  • ghci> goal2 " pen pen pen pen pen" "ppppp"
Ethan Lim
  • 73
  • 7
0

You forgot to implement the case where the string contains exactly one character. If you perform recursion, where we each time move two steps further, then eventually we will end at the empty string (list), or a string (list) with one character.

You thus should consider this with:

goal2 :: String -> String
goal2 [] = []
goal2 [x] = …
goal2 (h : m : t)
  | h == ' ' && m /= ' ' = m : goal2 t
  | h /= ' ' && m == ' ' = goal2 t
  | m == ' ' = goal2 t
  | otherwise = goal2 t

where I leave implementing the part as an exercise.

You goal2 will however still not work with " pen pineapple appen pen", since the cursor will stop at:

 pen pineappleappen pen
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^

This will result in ppn. This is because you each time move the cursor two places, whereas if a space is encountered, you might want to move the cursor a single place such that it can inspect the next character. This will also make your function simpler, and thus less error-prone.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I have answered your exercise with [h]=[h], and yea the result is 'ppn'. Due to only six hours of learning, can you give me some time about how to get the next letter of 'head'.I've only learnt how to retrieve the 'head' and all the 'tail' letters. – Ethan Lim Jun 28 '21 at 14:37
  • @EthanLim: work with a pattern `goal2 (h:ts)`, to move the cursor one item to the right if you recurse on `ts`. – Willem Van Onsem Jun 28 '21 at 14:40
  • @EthanLim: another wy to make only one hop is with `goal2 (m:ts)`. – Willem Van Onsem Jun 28 '21 at 14:43