How to bind to foreach context?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 12:21:07

问题


Currently I have this snippet of code:

    Blocks: ["F4369RO771" "282273" "5" "146" "126" "6-Nov-2009" "8-Jan-2010" "7-Jun-2010" "8"
"M9881KI923" "399727" "2" "359" "443" "5-Aug-2010" "23-Feb-2010" "6-Nov-2009" "4"
]

save-blocks: func[file /local f out][
    foreach [field1 field2 field3 field4 field5 field6 field7 field8 field9] blocks [

out: copy ""
repeat n 9 [
  part: get bind to-word rejoin ["field" n] 'field1 
  out: rejoin [out part ";"]
]
        remove back tail out
        write/lines/append f out


]

It's not generic enough, I'd like to pass this instead

block: [field1 field2 field3 field4 field5 field6 field7 field8 field9]

as parameter and write something like this:

save-blocks: func[block file /local f out][
    foreach block blocks [

out: copy ""
repeat n length? block [
  part: get bind to-word rejoin ["field" n] 'field1 
  out: rejoin [out part ";"]
]
        remove back tail out
        write/lines/append f out


]

But I don't know how to bind in this case too hard for me :(


回答1:


(For the moment, disregarding the question of whether what you're doing here is a good idea. :P)

Remember that when you pass a block! to foreach, it will bind the words inside that block during the loop:

>> foreach [foo bar] ["a" "b"] [print foo print bar]
a
b

When you pass a word! of any kind, it will be overwritten completely and no variables will be assigned (regardless of whether that word was bound to previously to a block!):

>> foobarblock: [foo bar]

>> foreach foobarblock ["a" "b"] [print foo print bar]
** Script error: foo has no value
** Where: foreach
** Near: foreach foobarblock ["a" "b"] [print foo print bar]

>> foreach foobarblock ["a" "b"] [print foobarblock]
a
b

To get the effect you seem to be desiring here, you need something like:

>> foreach :foobarblock ["a" "b"] [print foo print bar]
a
b

The behavior would then be what you expect, with the words bound in the local context.



来源:https://stackoverflow.com/questions/2775701/how-to-bind-to-foreach-context

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