Group Abstract Group Abstract

Message Boards Message Boards

1
|
3.9K Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

[?] Best way to model domain-specific concepts with Wolfram language?

Hi,

I'm just wondering what would be the best choice to model a domain-specific concept. If I take as an example the concept of a pet, with a name and a size. I see two options:

createPet[name_String, size_Real] := aPet["name"->name,"size"->size];

or

createPet[name_String, size_Real] := {"name"->name,"size"->size};

The first option allows me to use the Head aPet in my patterns. But it seems to me that the extraction of raw data is more verbose:

lotOfPets = {aPet["name"->"name1","size"->size1], aPet["name"->"name2","size"->size2],...};
lotOfPets /. aPet[___,"size" -> size_Integer, ___] -> size;
(* OR *)
Last/@Last/@lotOfPets (* I don't like this one because it is tightly linked to fixed positions in the expression*)

The second option allows me to more easily extract data using ReplaceAll:

lotOfPets = {{"name"->"name1","size"->size1},{"name"->"name2","size"->size2},...};
Flatten["size"/.lotOfPets]

What do you think?

Best

Fabrice

POSTED BY: Fabrice Jossinet
3 Replies
POSTED BY: Szabolcs Horvát

You can try Association and Dataset:

petsDatabase = 
 Dataset[{Association["name" -> name1, "size" -> size1], 
   Association["name" -> name2, "size" -> size2]}]
petsDatabase[All, "name"]
petsDatabase[All, "size"]
POSTED BY: Gianluca Gorni

Right. But my question was more about the best choice in a modeling process between a built-in data structure with all its advantages (like the practical way to query a Dataset or the easy way to extract the elements of a List with ReplaceAll) and a user-defined data structure (an expression with a user-defined Head). Then I remembered these Upvalues and Downvalues allowing you to setup operations linked to your Head. For example the cross between two pets with the operator +:

aPet /: aPet["name" -> name1_String] + aPet["name" -> name2_String] :=
   aPet["name" -> "My parents are " <> name1 <> " and " <> name2];
aPet["name" -> "Bob"] + aPet["name" -> "Brenda"]

Then no real best choice. I think it depends mainly if your domain-specific concepts are also linked to domain-specific operations.

Thank you for your answer.

POSTED BY: Fabrice Jossinet
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard