Search code examples
purescript

PureScript - Using Fat Arrow instead of Thin Arrow


Consider the following PureScript code, a slightly modified version of an example from the handbook:

module ArrayRecursion where

import Prelude (discard, Unit)
import Data.Array (null, tail)
import Data.Maybe (fromMaybe)

length :: forall a. Array a => Int
length arr = 
  if null arr then
    0
  else
    1 + ( length $ fromMaybe [] $ tail arr)

Compiling this code produces the following error

Unknown type class Array

So the code won't compile.

The questions:

  1. From where is the type class Array imported? It does not seem to be imported from Prelude or Data.Array.

  2. How does one go about finding where to import PureScript type classes? In this case, searching Pursuit for "Array" yields hundreds of results, creating a needle-in-haystack problem.


Solution

  • Array is not a type class, but a type.

    You accidentally put a fat arrow after Array a instead of a thin arrow, making it look like you were declaring a value of type Int with a constraint Array a rather than a function that takes an Array a as a parameter and returns an Int. This is how it should look:

    length :: forall a. Array a -> Int
    

    Normally you don't import the Array type. It's in the module called Prim, which is always implicitly imported.

    As for finding out - yes, search on Pursuit. If you carefully look at the search results, you will notice that only one of them (the first one) is actually a type. All the other ones are either functions or ADT cases.

    Another way to search for things (especially things in the standard libraries) is your IDE integration. These days I almost never actually have to manually add an import at the top of my files. I just start typing the name of whatever it is I need, and the IDE support offers me some options, waits for me to choose, and automatically adds an import. 10/10 recommend.