Parsing Strings
A client new to Magik recently contacted me. He was frustrated with his failure to find out how to parse a string. While Magik, with its class browser, it much easier than most languages to figure this out, it can still be frustrating. The help files shipped with Smallworld are excellent and I recommend reading them often. They are very voluminous, but just read the section that prompted your search and then remember to return to it whenever you want a better understanding of the concept in question.
That said, the help files aren't the best place to search for this information. The class browser is usually your best bet. Fire that baby up (F3 F3) and enter "string" for the class. Now you have to guess what the method will be called. "parse" would certainly be your first guess in this case. Unfortunately, that isn't what the method is called and hence my client's frustration. Here there should be a topic in the help files to cover this very important area, but there isn't. So now you just have to guess. What is parsing? It is splitting up one string into many strings. So, if you search on "split" you'd find the method split_by(), which takes a single argument: a character upon which to split the string. Here's an example from the Magik prompt:
This client also wanted to turn a string of number characters into a number. There are a couple of ways to do this but the most natural is to use the as_number() method on string. This pattern is used often and many objects have as_object_class methods defined on them for conversion. Here is an example:
MagikSF> "123".as_number()
$
123
That said, the help files aren't the best place to search for this information. The class browser is usually your best bet. Fire that baby up (F3 F3) and enter "string" for the class. Now you have to guess what the method will be called. "parse" would certainly be your first guess in this case. Unfortunately, that isn't what the method is called and hence my client's frustration. Here there should be a topic in the help files to cover this very important area, but there isn't. So now you just have to guess. What is parsing? It is splitting up one string into many strings. So, if you search on "split" you'd find the method split_by(), which takes a single argument: a character upon which to split the string. Here's an example from the Magik prompt:
MagikSF> "123,456,hi joe".split_by(%,)
$
sw:simple_vector:[1-3]
MagikSF> print(!)
$
simple_vector(1,3):
1 "123"
2 "456"
3 "hi joe"
This client also wanted to turn a string of number characters into a number. There are a couple of ways to do this but the most natural is to use the as_number() method on string. This pattern is used often and many objects have as_object_class methods defined on them for conversion. Here is an example:
MagikSF> "123".as_number()
$
123

0 Comments:
Post a Comment
<< Home