How do I convert set-words in a block to words
Asked Answered
V

6

6

I want to convert a block from block: [ a: 1 b: 2 ] to [a 1 b 2]. Is there an easier way of than this?

map-each word block [ either set-word? word [ to-word word ] [ word ] ]

Veator answered 10/5, 2013 at 5:34 Comment(0)
I
4

Keeping it simple:

>> block: [a: 1 b: 2]
== [a: 1 b: 2]
>> forskip block 2 [block/1: to word! block/1]
== b
>> block
== [a 1 b 2]
Ignatzia answered 10/5, 2013 at 11:40 Comment(0)
T
3

I had same problem so I wrote this function. Maybe there's some simpler solution I do not know of.

flat-body-of: function [
    "Change all set-words to words"
    object [object! map!]
][
    parse body: body-of object [
        any [
            change [set key set-word! (key: to word! key)] key 
            | skip
        ]
    ]
    body 
]
Trucking answered 10/5, 2013 at 7:8 Comment(1)
You should use ANY instead of SOME in there, also, you should use the SKIP keyword instead of ANY-TYPE!Ardine
C
2

These'd create new blocks, but are fairly concise. For known set-word/value pairs:

collect [foreach [word val] block [keep to word! word keep val]]

Otherwise, you can use 'either as in your case:

collect [foreach val block [keep either set-word? val [to word! val][val]]]

I'd suggest that your map-each is itself fairly concise also.

Centre answered 10/5, 2013 at 7:22 Comment(1)
These collect keep approaches are very elegantVeator
K
1

I like DocKimbel's answer, but for the sake of another alternative...

for i 1 length? block 2 [poke block i to word! pick block i]
Kerrison answered 10/5, 2013 at 12:6 Comment(0)
V
0

Answer from Graham Chiu:

In R2 you can do this:

>> to block! form [ a: 1 b: 2 c: 3]
== [a 1 b 2 c 3]
Veator answered 10/5, 2013 at 5:34 Comment(2)
A clever but... hackish solution. To string and back? :-/ I feel like there's a sort of essential complexity to the problem as you stated it, and the solution from your question kind of corresponds to that in the DO dialect. It's just an issue of in place vs. out of place, etc. Can you give any more context on what you're doing?Meilhac
The context is trying to convert rgchris's Twitter client to R3 - reb4.me/r/twitter - in the sign function there is a difference in behaviour here between r2 and r3 params: make oauth any [params []] params: sort/skip third params 2 (even after I have replaced the third with body-of) :-/Veator
S
0

Or using PARSE:

block: [ a: 1 b: 2 ]
parse block [some [m: set-word! (change m to-word first m) any-type!]]
Sestos answered 10/5, 2013 at 14:10 Comment(1)
Oh I didn't see that this solution is already suggested. Sorry.Sestos

© 2022 - 2024 — McMap. All rights reserved.