1

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
6
  • Think about what deleteLast "a" should be. This is the same of deleteLast ('a':[]), so you have to fix the line deleteLast (h:[]) = h. That's not all you have to do, but it's a start. Commented Jun 19, 2021 at 10:48
  • Also, see what happens if the input is "Empty list!!", the caller will not be able to distinguish the error from the correct result. Use the error function or the Either type as return value. Commented Jun 19, 2021 at 11:02
  • The initial title of the question could have mislead users into thinking one had to determine whether an input character was a letter or not, using for example library function isLetter. Commented Jun 19, 2021 at 14:54
  • 1
    Why can't you use init? Is this homework? Commented Jun 19, 2021 at 15:05
  • Yes, cannot use any predefined function in haskell Commented Jun 19, 2021 at 16:06

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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

2 Comments

Good ! But your last clause is neater when written as myLast (h:t) = h : (myLast t)
You can leave out the parens: myLast (h:t) = h : myLast t.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.