Search code examples
purescript

Map an Array of Values


Consider the following simple JavaScript function, which maps an array of numbers to the string number {number}:

function a(n){
  return `number ${n}`
}

[1,2,3].map(a);
// 'number 1', 'number 2', 'number 3'

What is the equivalent function in PureScript?

Searching Google or PureScript by Example for "Array Map" does not return any snippets or examples.

What is the PureScript equivalent, in the form of a PureScript snippet, to the above simple JavaScript function?


Solution

  • The function for mapping over an array in PureScript is called... (drumroll...) ... map! Surprise!

    (and in fact, the idea of "map", these days taken for granted, actually came into the so-called "mainstream" languages, such as JavaScript, from functional programming)

    In PureScript, however, the map function is generalized such that it applies to all sorts of things, not just arrays or lists. This is expressed in the Functor class. Both the class and the function are exported from Prelude, so there is no need to import anything extra.

    a :: Int -> String
    a n = "number " <> show n
    
    arr = map a [1,2,3]
    -- arr = ["number 1", "number 2", "number 3"]
    

    The map function also has two operator aliases: <$> for prefix application and <#> for postfix:

    arr1 = a <$> [1,2,3]
    arr2 = [1,2,3] <#> a
    

    The latter is particularly handy if you don't want to give your function a name:

    arr3 = [1,2,3] <#> \n -> "number " <> show n