1

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?

0

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

This answer came in handy yet again! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.