Constructing a map doesn't permit indexed collection as map key?

喜夏-厌秋 提交于 2020-01-11 07:19:38

问题


So I'm trying to actually write an answer to this question which seemed like an interesting one to me. What the hell, I'll give it a shot.

Here's the solution I came up with. It seems correct to me, and should yield the right result, but instead yields a cypher parse error.

So the game here is to take two collections (letters and numbers) and to construct a map out of them which maps the right letter to the right number, sequentially from the two collections.

My solution:

with [1,2,3] as nums, ['a', 'b', 'c'] as letters
with nums, letters, range(0, length(nums)-1) as idxs
return extract(idx in idxs | { letters[idx] : nums[idx] });

My reasoning is that I need to iterate over collection indexes so that I can use the same index to "advance both collections" at the same time. I'm using extract to get each index, then constructing the nested map, which pairs the appropriate items.

Except that it fails because cypher says:

Invalid input '[': expected an identifier character, whitespace, '}' or ':' (line 3, column 39 (offset: 140))
"return extract(idx in idxs | { letters[idx] : nums[idx] });"
                                       ^

UPDATE: cybersam answered the original question here and indicated that "it may not be possible to dynamically create map keys". So my real question is -- is that accurate (maps cannot have dynamic keys) and if so, why?


回答1:


This is just the "limitation" of cypher. You can try this:

WITH 'a' as key, 'test' as value
RETURN {key: value}

but the result is this:

{"key":"test"}

The correct approach is shown in the answer of Cybersam. Something like this:

WITH 'a' as key, 'test' as value, 'b' as key2, 'test2' as value2
RETURN [{key: key, value: value}, {key: key2, value: value2}]

will results:

[{"key":"a","value":"test"},{"key":"b","value":"test2"}]

For creating dynamic map keys you have to use java or other programming languages.



来源:https://stackoverflow.com/questions/29265673/constructing-a-map-doesnt-permit-indexed-collection-as-map-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!