Reputation: 93
I'm really new to Haskell programming. Can anyone help with this issues? -- delete the last character from a string in Haskell
deleteLast [] = "Empty list!" -- if the string is enpty
deleteLast (h:[]) = h -- recursion
deleteLast (h:t) = deleteLast t -- found the last character
result1 = [x | x == deleteLast , x /= deleteLast t] -- trying to remove the last character found
from the string
Upvotes: 1
Views: 3098
Reputation: 93
myLast :: [a] -> [a]
myLast [] = error "Empty list!"
myLast [h] = []
myLast (h:t) =[h]++myLast t
Output:
ghci> myLast "pineapple"
"pineappl"
ghci> myLast "pen"
"pe"
Thanks for the tips. @William Van Onsem
Upvotes: 2
Reputation: 476557
The return type of the deleteLast
is the same type as the item of the list. Indeed, the second clause specfies:
deleteLast (h:[]) = h
here h
is the head of the list, and thus the first item. The pattern (h:[])
is equivalent to [h]
, so this fires if there is a list with one element. In that case we return that singe element.
In case a list contains one element, we have to remove that element from the list (1). If we work with a list with at least two elements, we should yield the first item of that list, and recurse on the tail of the list:
deleteLast :: [a] -> [a]
deleteLast [] = error "Empty list!"
deleteLast [h] = … -- (1)
deleteLast (h:t) = … deleteLast t -- (2)
I leave implementing the second and third clause as an exercise.
Upvotes: 4