Home Programming Haskell Haskell: How To Rewrite The “Last” Function from Scratch

Haskell: How To Rewrite The “Last” Function from Scratch

Haskell, Last Function from Scratch

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.

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.

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.

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