Problem

Generate a new map by applying a function to each value in a map.

Solution

Applies to MarkLogic versions 7+

The local:apply-to-map() function takes a function to apply to each value, as well as a map to work on.

declare function local:apply-to-map(
  $function as xdmp:function,
  $mapIN as map:map
) as map:map
{
  map:new(
    (: Uses the simple map operator; see discussion below :)
    map:keys($mapIN) ! map:entry(., xdmp:apply($function, map:get($mapIN, .)))
  )
};
​
declare function local:plus-one($n)
{
  $n + 1
};
​
(: example run :)
let $map := 
  map:new((
    map:entry("foo", 1),
    map:entry("bar", 2),
    map:entry("stuff", 3),
    map:entry("nonsense", 4)
  ))
return local:apply-to-map(
  xdmp:function(xs:QName("local:plus-one")),
  $map
)

Discussion

In XQuery, as in a number of other languages, functions are items that we can pass around. That allows us to set up a function that will apply another function in some way. In this case, we’re looping through the keys of an input map applying the specified function to each value.

Notice that the function returns a new map with the changed values. It’s also possible to write a function like this that will modify the map in place, but returning a new map is more in keeping with functional programming.

The function to be applied can do whatever you want. The key element is that it needs to take a single value and return a new value. In the example, these values are simple numbers, but they could be XML nodes, sequences, strings, or whatever your application calls for.

The key line in local:apply-to-map is

map:keys($mapIN) ! map:entry(., xdmp:apply($function, map:get($mapIN, .)))

This line uses the simple map operator !, which applies some code to each item in a sequence. The same line can be written as a FLWOR statement, which is equivalent, but a bit less succinct:

for $item in map:keys($mapIN)
return map:entry($item, xdmp:apply($function, map:get($mapIN, $item)))

With the simple map operator, the period acts as the current item.

Learn More

Application Developer's Guide

Read the methodologies, concepts, and use cases related to application development in MarkLogic Server, with additional resources.

MarkLogic Developer Learning Track

Want to build that awesome app? Get off the ground quickly with the developer track, with instructor-led and self-paced courses.

Getting Started Video Tutorials for Developers

This series of short videos tutorials takes developers who are new to MarkLogic from download to data hub, fast.

This website uses cookies.

By continuing to use this website you are giving consent to cookies being used in accordance with the MarkLogic Privacy Statement.