Recombining pieces in Expr objects?

81 views
Skip to first unread message

Eric Jang

unread,
Aug 28, 2013, 4:45:02 PM8/28/13
to juli...@googlegroups.com
I'm trying a fun little experiment where I try to build a Tierra-like program with a few lines of Julia code.
I thought that the metaprogramming thing would be really suitable for this.

Basically I have an expression object that converts itself to a string, mutates it by flipping some bits, and then tries to parse it and evaluate it. If it fails, then it discards the changes.

I have a couple questions:

- to avoid huge amounts of syntax errors I would like to recombine on an expression level rather than on the bitstring level. Are there any facilities to allow the manipulation of Expr objects? For example, drilling down into sub-expressions?
- if not, how can I convert a string into a BitArray, then back?

e = quote
s = string(e)
o = s # backup
# mutate the string 
# somehow convert string to BitArray
b = BitArray(10000) # plus extra buffer to allow program to expand in size
f = rand(len(b)) < 1/len(b)
flipbits!(b[f])
#somehow convert back to string
try:
# convert back to string
e = parse(s)
eval(e)
catch:
print('something broke, reverting')
e = parse(o)
eval(e)
end

Alessandro "Jake" Andrioni

unread,
Aug 28, 2013, 5:47:49 PM8/28/13
to juli...@googlegroups.com
I'm not sure about converting strings to BitArrays and back, but it's
easy to convert strings to arrays of unsigned integers and back:

s = "A sample string"
array = uint8(collect(s))
# flipping all bits
~array

# flipping a random bit
i = rand(0:7)
array[rand(1:end)] $= (0x01 << i)

# flipping random bits
for i = 1:length(array), bit = 0:7
if rand() < 1/(length(array)*8)
array[i] $= (0x01 << bit)
end
end

# converting back to a string
s = bytestring(array)

Eric Jang

unread,
Aug 28, 2013, 7:00:12 PM8/28/13
to juli...@googlegroups.com
this should work, thanks very much.

Reply all
Reply to author
Forward
0 new messages