5

I am transferring between NetLogo and igraph (in R). Some of the information returned from igraph is 2-level nested lists of strings. Typical example looks like:

[ ["1" "2" "3"] ["4"] ]

I want to convert the internal strings into numbers, while retaining the list structure. So the example would become:

[ [1 2 3] [4] ]

I am guessing I need a combination of map and read-from-string (and perhaps other list manipulation like lput and foreach due to the nesting), but I just can't make it work.

Any ideas?

JenB
  • 17,620
  • 2
  • 17
  • 45

2 Answers2

6

Essentially, map each list to a mapped list with only int values. Try the following:

show map [ map [ read-from-string ? ] ?] [ ["1" "2" "3"] ["4"] ]
mattsap
  • 3,790
  • 1
  • 15
  • 36
  • thanks, I will go and code it up for the real example and see how i go – JenB Apr 14 '16 at 14:16
  • 1
    You actually don't need the square brackets around the `read-from-string`. You can just do `map [ map read-from-string ?] ...`. – Bryan Head Apr 14 '16 at 15:21
5

Just for fun, here is a version that can convert an arbitrary number of nested levels:

to-report read-from-list [ x ]
  report ifelse-value is-list? x
    [ map read-from-list x ] 
    [ read-from-string x ]
end

Example:

observer> print read-from-list [ ["1" "2" "3" ] ["4" [ "5" "6" ] ] ]
[[1 2 3] [4 [5 6]]]
Nicolas Payette
  • 14,847
  • 1
  • 27
  • 37