Solved: get first char from string

In the world of programming, a common yet significant task is extracting specific elements from a dataset, like the first character of a string. Here, we will focus on Haskell, a modern, purely functional programming language known for its high degree of modularity, rich set of features and strong type safety. Our task is simple – retrieve the first character from a string. But before we dive into it, it’s essential to understand that strings in Haskell are simply lists of characters. This means we will utilize list operation tactics to achieve our aim.

Using the Head Function

One known method of selecting the first character of a string is using the native ‘head’ function in Haskell. Let’s illustrate this with an example:

getFirstChar :: String -> Char
getFirstChar = head

In this example, the function `getFirstChar` employs the ‘head’ function, which extracts the first element from a list (characters list in our case). The input is a ‘String’, and the return type is ‘Char’ – the first character of the string.

Understanding the Code

Let’s break it down step by step for a more profound understanding. Firstly, we declare a function `getFirstChar` which takes a `String` type as input and returns a `Char` type. This is specified by `getFirstChar :: String -> Char`.

In the function definition, we use the `head` function, a built-in Haskell function used to retrieve the first item from a list.

More on the Head Function

While handling Haskell, specifically while managing lists, the ‘head’ function appears frequently. In a nutshell, any list in Haskell has two parts: the head and the tail. The head function retrieves the first element (or the head) of the list.

There’s only one thing to be careful of: the ‘head’ function should not be used on an empty list. If it is, it will result in a runtime error.

Error Handling and the ‘Safe’ Library

While using `head` as we did is simple, it does come with its risks. As mentioned, calling `head` on an empty list will result in an error. Here enters the ‘Safe’ library which provides versions of functions that won’t crash on exceptional input and allow safer Haskell code.


import Safe (headMay)

getFirstCharSafe :: String -> Maybe Char
getFirstCharSafe = headMay

Using `headMay` from the ‘Safe’ library, the function `getFirstCharSafe` now returns a Maybe Char, which can be a `Just Char` if the string is non-empty or `Nothing` if it’s empty.

With these concepts, you can confidently manipulate strings and retrieve the first character in Haskell, keeping in mind potential exceptions and ways to handle them. Hope this helps you on your Haskell journey. Happy coding.

Related posts:

Leave a Comment