Skip to content

Commit 22925a6

Browse files
committed
Example for custom code
1 parent 9bac746 commit 22925a6

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

examples/customcode.jl

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
using AcuteML
2+
# Definition
3+
@aml mutable struct Student "student"
4+
5+
# add custom code to the begining of creator function
6+
# the following automatically fills IQ based on the name
7+
@creator begin
8+
if occursin("smart", name)
9+
name = replace(name, "-smart" => "") # remove smart from name
10+
IQ = "smart"
11+
elseif occursin("genius", name)
12+
name = replace(name, "-genius" => "") # remove smart from name
13+
IQ = "genius"
14+
else
15+
error("Give a smart student.")
16+
end
17+
end
18+
19+
name::String, "~"
20+
GPA::Float64, "~"
21+
IQ::UN{String} = nothing, att"~" # default to nothing, but filled automatically by first @cretor macro
22+
# add custom code to the end of extractor function
23+
24+
log::UN{String} = nothing, "~"
25+
26+
@extractor begin
27+
if GPA > 4.0
28+
log = "A genius with a GPA of $GPA is found" # setting fields using @extractor only changes the field and not the xml code
29+
end
30+
end
31+
end
32+
33+
@aml mutable struct MathClass "math-class"
34+
@creator begin
35+
GPAsum = 0.0
36+
for student in students
37+
GPAsum = GPAsum + student.GPA
38+
end
39+
average = GPAsum / length(students) # fill average field
40+
end
41+
42+
students::Vector{Student}, "student"
43+
average::UN{Float64} = nothing, "average" # calculated automatically
44+
end
45+
46+
################################################################
47+
# Creation
48+
smarts = [Student(name = "Jack-smart", GPA = 2.0), Student(name = "Sara-genius", GPA = 5.0)]
49+
mathclass = MathClass(students = smarts)
50+
51+
mathclass.students[1].name # "Jack"
52+
mathclass.students[2].name # "Sara"
53+
mathclass.average # 3.5
54+
55+
pprint(mathclass)
56+
# <math-class>
57+
# <student IQ="smart">
58+
# <name>Jack</name>
59+
# <GPA>2.0</GPA>
60+
# </student>
61+
# <student IQ="genius">
62+
# <name>Sara</name>
63+
# <GPA>5.0</GPA>
64+
# </student>
65+
# <average>3.5</average>
66+
# </math-class>
67+
68+
################################################################
69+
# Extraction
70+
71+
xml = parsexml("""
72+
<math-class>
73+
<student>
74+
<name>Jack</name>
75+
<GPA>2.0</GPA>
76+
</student>
77+
<student>
78+
<name>Sara</name>
79+
<GPA>5.0</GPA>
80+
</student>
81+
<average>3.5</average>
82+
</math-class>
83+
""")
84+
85+
mathclass = MathClass(xml)
86+
87+
mathclass.students[2].log # "A genius with a GPA of 5.0 is found"

0 commit comments

Comments
 (0)