4xx
4xx

Reputation: 185

Haskell: NonEmpty

I'm learning Haskell and trying to see how NonEmpty works. I've written the following code.

module Mm (main, Bb, g) where

import Data.List.NonEmpty

g :: NonEmpty Integer -> NonEmpty Integer
g  = fmap (+9) 
main = g

It compiles, but when I do:

b= nonEmpty [2,3]
main b

an error shows up. I don't understand where I'm doing something wrong!

Edit: I get the following error:

couldn't match expected type 'NonEmpty Integer' with actual type 'Maybe 
(NonEmpty Integer)'.  In the first argument of 'main' namely 'b'.
In the expression: main b
In an equation for 'it' : it = main b

Upvotes: 1

Views: 1835

Answers (1)

SwiftsNamesake
SwiftsNamesake

Reputation: 1578

Look at the type of nonEmpty. What should the result of nonEmpty [] be? You're getting a type error, because nonEmpty has to return a Maybe (NonEmpty a), or it would be a partial function (possibly crashing at runtime if you ever try to access the value).

Solution

There are a few ways to resolve the problem. One is to use maybe to choose an action depending on the outcome:

maybe (Left "List is empty") (Right . main) $ b

Another is to pattern match on the result, assuming it's never Nothing. If this assumption ever turns out to be wrong, your program will crash at runtime:

let (Just b) = nonEmpty [2,3] in main b

A third choice that I neglected to mention is to use the constructor for NonEmpty directly:

main $ 2 :| [3]

This is probably the solution you're looking for. The route via lists is simply an annoying detour, for the reasons I've stated above.

Upvotes: 4

Related Questions