Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
haskell

How to get the last element of a list in Haskell

Chinweuba Elijah Azubuike

The last method

The last method gets the last element of a Haskel list.

A Haskell list can be of any data type, a string of letters, an array of numbers, etc.

Why get the last element of a list?

Getting the last element of a list can come in handy while working with arrays. Like in functions where we add into an array or remove from it, we will want to know the last element in the array after the action.

Syntax of the last method

last list

Parameter

The last method takes the list as a parameter.

Code

Let’s look at the executable code below to see how we can get the last element:

main = do 
  let x = [1,3,5,7,9]
  print(last x)

Explanation

  • Line 2: We declare a variable x and assign an array of numbers to it.
  • Line 3: To get the last element in the list, we use the print() method. Here, we pass the last() function with the list as an argument.

RELATED TAGS

communitycreator
haskell

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring