Just finished a Computer Science lecture today, and two of the main questions that stumped me in our lab tasks were on rewriting the “last” and “init” functions in Haskell. The post will show you my approach.

What Is The “Last” Function

I’m going to assume you’ve touched on the most-very basic parts of Haskell. But just to show you guys, here’s a little demonstration.

--Firstly we're going to define a little function that 
--takes in a list, [Int]
--and returns the last element, Int

lastDemo :: [Int] -> Int

--then we'll set up the returning part

lastDemo x = last x

-----------------------------
-- This takes some list x, and returns the last element of this list

How To Rewrite The Last Function

In this snippet, we simply reference the last index in the list. To do this we take the length of the list and minus 1. We minus 1 because index’s start from 0, however length counts starting from 1.

--Again we start with a function that takes [Int] and outputs Int

lastV2 :: [Int] -> Int

-- And we're going fetch the last element in the array
-- by using the "length" of the array, minus 1

lastV2 x = x !! (length x - 1)

-- note the "!!" means index

Another Approach The You Could Use

In this snippet, we use the drop function to shorten the array down to the last element. Once we’ve got the single element array, we need to call the 0th element so that we can return its value; without calling the element we will return an object of type [Int], however the output specified is Int.

--In this case

lastV3 :: [Int] -> Int
lastV3 x =  (drop (length x - 1) x)!! 0

-- We're using the drop function to drop all but the last element
-- Then we call the 0th element on the array because we need the value
-- From the given element

--## EXAMPLE INPUT & EXPECTED OUTPUT ##--
--> lastV3 [3,4,5,6,7,8,9,90,124910401294,78]
--> 78

How To Use The Code Above

Well, first you need something to interpret your code. Go with GHCI, and simple command line program that will run your software. And secondly, you need to save the code in a file that has a “.hs” file extension.

Once you’ve done both of the above, find your file, load it into your software and hey presto.

Until next time, Josh

Leave a Reply
You May Also Like

How To Make Money from Pokemon-Go Going Viral

I think everyone’s heard about the new Pokémon game that’s just come…

Making Clickbait Thumbnails with Canva, that Grab People’s Attention

A good, clickbait thumbnail will get people clicking your articles and YouTube…

Shopify Dropshipping: How to Make Money Dropshipping on Shopify

Shopify and dropshipping tend to go hand-in-hand nowadays. For the longest time,…

Free Traffic: How to Get Free Traffic using Quora

Quora isn’t the newest thing out there, but that doesn’t matter, it…