VictorAladjev,VjacheslavVaganov
ExtensionofMathematicasystem
functionality
Tallinn–2015
ExtensionofMathematicasystemfunctionality:VictorAladjev,VjacheslavVaganov.–
Tallinn:TRGPress,563p.,2015
Systemsofcomputermathematicsfindmoreandmorebroadapplicationinanumberof
natural,economicalandsocialfields.Thesesystemsareratherimportanttoolsfor
scientists,teachers,researchersandengineers,verywellcombiningsymbolicalmethods
withadvancedcomputingmethods.Oneofleadersamongmeansofthisclassundoubtedly
istheMathematicasystem.Thebookfocusesononeimportantaspect–modular
programmingsupportedbyMathematica.Thegivenaspectisofparticularimportancenot
onlyforappendicesbutalsoaboveallitisquiteimportantinthecreationoftheuser
meansthatexpandthemostfrequentlyusedstandardmeansofthesystemand/oreliminate
itsshortcomings,orcomplementthenewfacilities.
Softwaretoolspresentedinthebookcontainanumberofratherusefulandeffective
methodsofproceduralandfunctionalprogramminginMathematicasystemthatextendthe
systemsoftwareandallowsometimesmuchmoreefficientlyandeasilytoprogramthe
objectsforvariouspurposesfirstofallwearingsystemcharacter.Theabovesoftware
toolsratheressentiallydilatetheMathematicafunctionalityandcanbeusefulenoughfor
programmingofmanyapplicationsaboveallofsystemcharacter.Furthermore,thebookis
providedwithfreewarepackageAVZ_Packagecontainingmorethan680procedures,
functions,globalvariablesandotherprogramobjects.Thepresentbookisorientedona
wideenoughrangeofusersofsystemsofthecomputermathematics,teachersand
studentsofuniversitiesatcoursesofcomputerscience,mathematicsandother
natural–sciencedisciplines.
Inthecourseofpreparationofthepresentbookthelicensereleases8÷10of
theMathematicasystemprovidedbyWolframResearchInc.havebeenused.
©VictorAladjev,VjacheslavVaganov.Allrightsreserved.PrintedbyCreateSpace,An
Amazon.comCompany
Contents
Preface5
Chapter1.AdditionalmeansininteractivemodeoftheMathematica13
Chapter2.AdditionaltoolsofprocessingofexpressionsintheMathematicasoftware26
Chapter3.Additionalmeansofprocessingofsymbolsandstringstructuresin
theMathematicasystem58
Chapter4.AdditionalmeansofprocessingofsequencesandlistsintheMathematica
software81
Chapter5.TheadditionalmeansexpandingthestandardMathematicafunctions,orits
softwareasawhole101
5.1.ThecontrolbranchingstructuresandcyclicstructuresintheMathematicasystem123
5.2.ThecycliccontrolstructuresoftheMathematicasystem127
Chapter6.ProblemsofproceduralprogrammingintheMathematicasoftware130
6.1.DefinitionofproceduresintheMathematicasoftware130
6.2.DefinitionoftheuserfunctionsandpurefunctionsinsoftwareoftheMathematica
system146
6.3.MeansoftestingofproceduresandfunctionsintheMathematicasoftware154
6.4.HeadingsofproceduresandfunctionsintheMathematicasystem182
6.5.Formalargumentsofproceduresandfunctions;themeansofprocessingthemin
theMathematicasoftware207
6.6.Localvariablesofmodulesandblocks;themeansofmanipulationbythemin
theMathematicasoftware235
6.7.Globalvariablesofmodulesandblocks;themeansof
manipulationbythemintheMathematicasoftware259
6.8.Attributes,optionsandvaluesbydefaultfortheargumentsoftheuserblocks,
functionsandmodules;additionalmeans
ofprocessingofthemintheMathematicasystem275
6.9.Someadditionalfacilitiesforoperatingwithblocks,functionsandmodulesin
theMathematicasoftware292
Chapter7.Meansofinput–outputoftheMathematica354
7.1.MeansoftheMathematicaforworkwithinternalfiles354
7.2.MeansoftheMathematicasystemforworkwithexternalfiles369
7.3.MeansoftheMathematicasystemforprocessingofattributesofdirectoriesand
datafiles385
7.4.Additionalmeansofprocessingofdatafilesanddirectories396
7.5.Certainspecialmeansofprocessingofdatafilesanddirectories420
Chapter8.ThemanipulationsorganizationwiththeuserpackagesintheMathematica
software431
8.1.Conceptofthecontext,anditsuseinthesoftwareofthe
Mathematicasystem432
8.1.1.InterconnectionofcontextsandpackagesinthesoftwareoftheMathematicasystem
437
8.2.Definitionoftheuserpackages,andtheirusageinthe
Mathematicasoftware440
8.3.AdditionalmeansofoperatingwithpackagesintheMathematica473
8.4.TheorganizationoftheusersoftwareintheMathematicasystem534
8.5.ApackagefortheMathematicasystem550
References553
Monographs,textbooksandbooksoncomputerscience,
theoryofgeneralstatistics,cellularautomatatheoryand
computermathematicssystems,preparedandpublishedbymembersoftheBaltic
Branchduring1995–2015558
AbouttheAuthors563Mathematica2,5÷10–trademarksofWolframResearchInc.
Preface
Systemsofcomputermathematics(SCM)findmoreandmorewideapplicationina
numberofnatural,economicalandsocialsciencessuchas:informatics,chemistry,
mathematics,physics,technologies,education,economics,sociology,etc.Suchsystems
asMathematica,Maple,REDUCE,MuPAD,Derive,Magma,Axiom,Maxima,GAP,
MathPiperandothersaremoreandmoredemandedforlearningofthemathematically
orienteddisciplines,invariousscientificresearchesandtechnologies.Thesesystemsare
themaintoolsforteachers,scientists,researchers,andengineers.Researchesonthebasis
oftechnologySCM,asarule,wellcombinealgebraicmethodswithadvancedcomputing
methods.InthissenseofSCM–interdisciplinaryareabetweeninformaticsand
mathematicsinwhichresearchesareconcentratedondevelopmentofalgorithmsfor
algebraical(symbolical)andnumericalcalculationsanddataprocessing,andoncreationof
programminglanguagesalongwithprogramenvironmentforrealizationofthiskindof
algorithmsandtasksofdifferentpurposewhicharebasedonthem.
Solutionofapplieduserproblemsinoneortheotherfieldofappendicesissupported
bypackagesofappliedprograms(PAPorsimplypackages)ofspecial,highlyspecialized
orgeneralpurpose.Classificationandcharacteristicofsuchclassofsoftwarecanbefound
inourpreviousbooks[3–5].Naturally,thequalifieduserwellowningoneofeffective
programminglanguages(forexample,Basic,C,Fortran,PL/1,Pascal,Lisp,Prolog,etc.)
inanumberofcasesforthesolutionofowntaskscanindependentlywriteanddebuga
separateprogramoracomplexofprogramsallowingtorealizealgorithmofitstasksona
personalcomputer.Insomecasessuchapproachcanbemoreeffective,thanuseforthese
purposesofreadysoftwaresincethesoftwaredeveloperatthesametimewellowns
specificsofthesolvedtaskandconditionsofitsoperation.However,suchapproach
demandsasaruleofseriouscostsandatpresentabundanceofvarioustypeandpurposeof
meansforapersonalcomputerbecomesconsiderablyinexpedient.Atthesametime,
developedPAParesuppliedwithownbuiltinprogramminglanguageofoneorotherlevel
ofcomplexityallowingtoprogramthewholetasksortheirseparatefragmentswhichmay
beintheenvironmentofapackageareinefficiently,inexpedient,andinsomecasesandis
impossibletorealizebythestandardmeansofapackage.
Thisbookisdevotedtotheclassofsoftwarecalledbysystemsofcomputermathematics
which,firstofall,areintendedforthesolutionofproblemsofmathematicalcharacter,
and,firstofall,toleadersinthisclasstosystemsMathematicaandMaple.Moreover,only
theindirectattentionconcerningcomparisonofsystemsoncertainseparatemomentsis
paidtothesecondsystemwhereasquitedevelopedtheircomparativeanalysiscanbe
foundinourbooks[28-30].Atthat,muchattentionwaspaidbothonexperiencewith
describedmeans,andfeaturesoftheirusage,andalsorecommendationsfortheuser
followingfromthem.Asfaraspossible,themosteffectivetechniqueofapplicationof
thesemeansforthesolutionofthoseorotherappliedusertaskshavebeenoffered.
Moreover,inbook[33]wepresentedanexcursusinhistoryofcomputeralgebrasystems
thatrepresentsacertaininterestfortheuserofthisclassofsoftware.Ratherdetailed
characteristicofthisseriesofbookscanbefound,inparticular,in[30-33]andinthe
presentbookisn’tconsidered.Ouroperatingexperiencewithsystemsofcomputeralgebra,
firstofall,MathematicaandMapleallowednotonlytocarryoutacomparativeanalysisof
thesemeans,torevealdeficienciesinherenttothem,andalsotocreateanumberofthe
meansexpandingtheirfunctionalityandeliminatingtheirsomedefects.Allthese
questionsincludingquestionsofterminologicalcharacterwithvariousextentofdetailing
havebeenconsideredinaseriesofourbooksandpapers[1-48].
TheMathematicasystemalongwiththeabove–mentionedMaplesystemisoneofthe
mostknownandpopularSCM,itcontainsaratherlargenumberoffunctionsforproviding
assymbolicaltransformations,andfornumericalcalculations.TheMathematicasystem
fortodayismultipurposemeansthatincludesalargenumberofopportunitiesforthe
solutionofquitewiderangeofproblems.Naturally,forthesemeanscan`tbegivena
ratherfullanalysiswithintheframeworkofthegivenbook.Furthermore,thetargetofthe
bookconsistsinother–inthebooktheattentionisfocusedonlyononeaspectofsystem–
opportunitiesofherprogramenvironmentforsolutionofspecialproblemsofmassand
systemcharacter.
Thisaspecthasthespecialimportancenotonlyforsolutionofappliedtasksbutaboveall
itisquiteimportantatcreationofthesoftwareexpandingoftenusedsystemmeansand/or
eliminatingtheirdefects,orsupplementingthesystemwithnewmeans.Inthiscontext
possibilitiesofbuilt–inlanguageofthesystemoncreationofsuchkindofproceduresor
functionsareofspecialinterest.So,programminginthesystemisamultifacetedsubject
andinitwefocusattentiononlyonquestionsofrealizationofprocedures/functionsthat
representmainprogramobjectsbothforthemostoftenusedmeansoftheuser,andforthe
meansexpandingandimprovingstandardsystemmeansinthesystemsoftware,i.e.
realizedbymeansofthebuilt–inlanguageofthesystem(Mathlanguage).Inthiscontextit
isalsopossibletoestimateinquitefullmeasuretheMathematicasystemsoftware,without
regardingtosomesubjectivemoments,firstofall,theuserpreferencesandhabits.
Naturally,thesemomentsplayaratheressentialpartfortheuserwhichhasacertain
experienceofworkwithprogramlanguagesofproceduraltypewhereasforabeginner
theystandnotsosharplybecauseoflackofsuchexperience.So,consideringorientation
ofthegivenbook,forconsciousacquaintancewithitscontentstheknowledge
ofMathlanguageatthelevelabovetheinitialissupposed,forexample,withintheworks
[29-33,51,52,55,57,60,62,64,66,71].Sincethe10thversionMath–languageiscalledas
WolframLanguagewhat,inouropinion,isresultofcertainpainfulambitionssimilarto
thosethatareassociatedwithbook”ANewKindofScience”alongwithafairshareof
self–advertisementofallegedlynewmeans.
ThegivenbookaffectsaratherextensivematerialonMathematicasoftwareinthecontext
ofitsopportunitiesinproceduralandfunctionalprogramming.Meanwhile,mainpurpose
ofthisbooklaidasidethequestionswhichareofinterest,firstofall,toreaderswhoarein
ownactivityatthefirststagesofanmasteringoftheMathematicasystem.Forbeginnersit
isrecommendedtoaddressoneselftothecorrespondingeditionswhoselistisrather
extensive,aboveall,theEnglish-language.TheMathematicasystemisconsideredandin
Russian–languageliterature,howeverEnglish–languageeditions,inouropinion,are
representedtousmorepreferable.Ingeneral,itispossibletofamiliarizeoneselfwith
literatureonthewebsitewww.wolfram.com/books,quiteusefulsourcescanbefoundinthe
representedreferences,includingaratherusefulreferencesintheInternet.
Thus,thegivenbookrepresentsacertainsetoftheselectedsystemproblemswhose
purposenotonlytoexpandormakemoreeffectivetheMathematicasystem,butalsoto
givecertainhelptothoseusersoftheMathematicawhowouldliketomovefromthe
user’sleveltoaleveloftheprogrammerortothosewhowhenusingMathematicaalready
facedsomeitsrestrictionsandwanttoimproveitsprogramenvironment.Atthat,the
skilledMathematicaprogrammersprobablywillalsobeabletofindforthemselvesinour
bookaratherusefulinformationandofappliedcharacter,andtoreflection.Therefore
illuminationonlyofsomequestionsessencewithouttheirratherdetaileddiscussion,
certainnuancesandconsiderationofadjacentquestionsthatareofteninterestingand
importantperseoftentakesplace.Moreover,thesystemmeanspresentedinthebookcan
beusedasratherusefulmeansatdevelopingownapplicationsintheenvironment
ofMathematica.Inouropinion,ananalysisofthesourcecodesofthemeanspresentedin
thisbookwhichusebotheffective,andnonstandardmethodsofprogrammingalongwith
quitecertainpracticalinterestwillallowtomastertheenvironmentofMathematica
systemmoredeeply.Forconvenienceoftheiruseinthegivenqualitythereaderhas
possibilityoffreedownloadofAVZ_PackagepackageforMathematicasystemof
versions8÷10whichcontainsthesemeans[48].Themeansconsideredthroughoutthe
presentbookanswerfullythemaingoaloftheofferedbookwhichcanbecharacterizedby
thefollowing2maindirections,namely:
(1)representationofanumberofusefulenoughmeansofsystemcharacterthatexpand
andsupplementstandardmeansoftheMathematicasystem;(2)illustrationontheir
exampleofreceptionsandmethods,enoughusefulinproceduralandfunctional
programming,alongwithanumberofessentialenoughfeaturesofthisparadigmof
programmingintheconditionsoftheprogramenvironmentoftheMathematicasystem.
Hereisquiteappropriatetonoteaquitenaturalmechanismofformationofownsoftware
meansoftheuserworkinginsomeprogramenvironment.Incourseofprogrammingof
oneorothermeans,orthewholeprojectacertainsituationisquiterealwhenisrather
expedienttoprogramsomeadditionaltoolsthatareabsentamongstandardmeans,either
theyaremoreeffective,ortheyaremoreconvenientthanstandardmeans.Inmany
importantcasestheapplicabilityofthesemeanscanhavemassenoughcharacter,allowing
toformprogramtoolkitofquitewiderangeofapplicability.
Exactlyinmanyrespectsthankstothedescribedmechanismwehavecreatedquitefamous
libraryUserLibforMaplealongwithpackageAVZ_PackageforMathematicawhich
containmorethan850and680meansrespectively[47,48].Allabove-mentionedmeansare
suppliedwithFreeWarelicenseandhaveopenprogramcode.Suchapproachto
programmingofmanyprojectsbothinMathematica,andinMaplealsosubstantially
promotedemergenceofanumberofsystemmeansfromabove–mentionedlibraryand
package,whendevelopmentofsoftwareforsimplificationofitsrealizationrevealed
expediencyofdefinitionofthenewaccompanyingtoolsofsystemcharacterthatarerather
frequentlyusedbothinappliedandinsystemprogramming.So,opennessof
theAVZ_Packagepackagecodeallowsbothtomodifythemeanscontaininginit,andto
programontheirbasisownmeans,ortousetheircomponentsinvariousappendices.In
ouropinion,tasksandmeansoftheirrealizationinMathematicawhicharepresentedin
theabovepackagecanberatherusefulatdeepermasteringofsystemandinanumberof
caseswillallowtosimplifyrathersignificantlyprogrammingofappendicesinit,firstof
all,thesystemproblems.Atthat,themethodologicalconsiderationsrepresentedinour
previousbooks[29-33]fullyremaininforceandrelativetothepresentbook.
MeansofAVZ_Packagepackagehavedifferentcomplexityoforganizationandused
algorithms;incertaincases,theyuseeffectiveandnonstandardreceptionsof
programminginMathematica.Thegivenmeanscanbeusedasindividually(forthe
decisionofvariousproblemsorforcreationontheirbasisofnewmeans),andinstructure
ofAVZ_PackagepackageextendingstandardtoolsoftheMathematica,eliminatinga
numberofitsdefectsandmistakes,raisingitscompatibilityrelativelytoitsreleasesand
raisingeffectivenessofprogrammingofproblemsinMathematica.Atoolrepresentedin
thebookissuppliedwithdescriptionandexplanations,containsthesourcecodeandthe
moretypicalexamplesofitsapplication.Asrequired,adescriptionhassuppliedby
necessaryconsiderations,concerningpeculiaritiesofprogramexecutionin
theMathematicaenvironment.
Thegivenbookconsiderscertainprincipalquestionsofprocedure–functional
programminginMathematica,notonlyforthedecisionofvariousappliedproblems,but,
firstofall,forcreationofthesoftwareexpandingfrequentlyusedfacilitiesofthesystem
and/oreliminatingtheirdefectsorexpandingthesystemwithnewfacilities.Thesoftware
presentedinthisbookcontainsaseriesofusefulandeffectivereceptionsofprogramming
inMathematicasystem,andextendsitssoftwarewhichenablesmoresimplyand
effectivelytoprogrammeinthesystemMathematicatheproblemsofvariouspurpose.The
representedmonograph,ismostlyforpeoplewhowantthemoredeepunderstandingin
theMathematicaprogramming,andparticularlythoseMathematicauserswhowouldlike
tomakeatransitionfromtheusertoaprogrammer,orperhapsthosewhoalreadyhave
certainlimitedexperienceinMathematicaprogrammingbutwanttoimprovetheir
possibilitiesinthesystem.WhereastheexpertMathematicaprogrammerswillalso
probablyfindanusefulenoughinformationforyourself.
Atthat,itshouldbenotedthatthesourcecodesofmeansgiveninthisbookcontaincalls
ofnon–standardtoolsthatdidn’tfindreflectioninthepresentbookinanumberofcases,
butarepresentedinourpackage[48].Therefore,theirdetailedanalysisrequires
acquaintancewiththesetools,atleast,atthelevelofusagesonthem.Meanwhile,the
mainalgorithmofmanymeansofthepresentedbookisratherwelllookedthroughand
withoutacquaintancewithsimilarmeanswhilerealuseofthesemeansperhapsonlyafter
loadingofthispackageintothecurrentsession.Alongwiththeillustrativepurposesthe
meansrepresentedinthismonographquitecanbeusedandasenoughusefulmeans
extendingtheprogramMathematicaenvironmentthatrathersignificantlyfacilitate
programmingofawiderangeoftheproblemsfirstofallhavingthesystemcharacter.Our
experienceofconductingofthemasterclassesofvariouslevelinsystems
andMathematica,andMapleconfirmsexpediencyofapplicationincommonwith
standardmeansofbothsystemsandsomeusertoolscreatedinthecourseofprogramming
ofappendices.Toolsrepresentedinthebookincreasetherangeandefficiencyofusageof
MathematicaonWindowsplatformowingtotheinnovationsinthreebasicdirections,
namely:(1)eliminationofaseriesofbasicdefectsandshortcomings,(2)extendingof
capabilitiesofaseriesofstandardtools,and(3)replenishmentofthesystembynewmeans
whichincreasecapabilitiesofitsprogramenvironment,includingthemeanswhich
improvethelevelofcompatibilityofreleases7–10.Atlast,withorganizationoftheuser
softwareandprogrammingoflarge-scalesystemsinMathematicasoftwarealongwithour
standpointonaquestion:MathematicaorMaple?theinterestedreadercanfamiliarizein
[29–33].Atlast,anumberofmeansrepresentedintheabovebooksisintendedfora
extensionofstandardmeansofthesystemsMathematicaandMaplealongwith
eliminationoftheirshortcomingsandmistakes.Thesemeansnotonlymoreaccurately
accentdistinctionsofbothsystems,butalsotheirproblemsofcommoncharacter.Andin
thisrelationtheyallowtolookfromdifferentpointsofviewontheseorotherboth
advantages,andshortcomingsofbothsystems.Inthepresentbookwepresentanumber
ofmeansofsimilartypeconcerningtheMathematicasystem.Atthat,itshouldbenoted
thatamassoptimizationofprocedureshavenotbeenperformed,proceduresinmany
caseshavebeenwritten,astheysayon’sheet‘;ontheotherhand,numerousprocedures
havebeenoptimizedusingboththestandardmeansandnewlycreatedtoolsofsystem
character.Inthiscontextherethereisamagnificentexperimentalfieldforincreasingof
professionalismoftheuseratoperatingwiththeMathematicasoftware.
Inclusionofsourcecodesoftheproceduresandfunctionspresentedinthisbookwiththeir
shortcharacteristicdirectlyinthebooktextallowstoworkwiththemwithoutcomputer,
consideringahabitofconsiderablenumberoftheusersoftheseniorgenerationtooperate
withprogramlistingsbeforeexittothecomputerwhatinaseriesofcasespromotedbetter
programminginduetimeatprogramminginbatchmode.Inouropinion,skilltooperate
withprogramlistingsisaratherimportantcomponentoftheprogrammerculture,allowing
bettertofeeltheusedprogramenvironment.Inacertainmeasureitissimilarto
possessionofthemusicianbythesheetmusic.
Moreover,manylistingsoftherepresentedmeanshavearathersmallsize,allowingto
analyzethemoutsideoftheMathematicaenvironmentintheassumptionthatthereaderis
sufficientlyfamiliarwithitssoftware.Now,atmassexistenceofpersonalcomputersof
varioustypethementionedvisualanalysisoftheprogramlistingswasreplacedwiththe
modeofinteractiveprogramming,howeverit’snotthesame,andinthefirstcasethe
processofprogrammingseemstousmorebetterandefficient.Meanwhile,eventoolswith
smallsourcecodeoftenareusefulenoughatprogrammingofvariousapplications,in
particular,ofsystemcharacter.Whereasothersdemandfortheunderstandingofserious
enoughelaboration,includingacquaintancewithourpackageAVZ_Package[48].
Asshowsourexperience,theprogrammingintheabovemodeslightlymoreslowly,than
directlyonthecomputer,howeveritallowstoconcentrateourbetteronanobjectof
programminganditisbettertothinkoveraproblemandawayofitsdecision,rather,than
methodofitsdecisionintheso-calledinteractivemode.Eveninthepresenceof
thepersonalcomputer(PC)wegotusedthebasicskeletonofaprogramtowriteonpaper
andonlythentopasstodebuggingontothepersonalcomputerintheinteractivemode.So,
inouropinion,suchapproachallowstowriteprogramsmorethoughtfully;atthat,
followingtheoldhabittowriteoptimalenoughcodesfortheirsubsequentperformanceon
quitelimitedcomputingresourcesofthecomputers20–30yearsago.However,inmany
respectsthisismatterofhabit,howeveryoushouldn’tforgetthattheoldisn’talways
worsethannewoneand,gettingnewopportunities,we,often,losetheoldskillsimportant
forwork.Hereandinthiscase,havingreceivedveryconvenientmeansof
communication,we,sometimes,losesightofefficiencyofaprogramcode,creatingit
withoutespecialdifficultiesintheinteractivemodewiththeonlypurposetoreceivethe
demandedresult,often,ignoringquality.
Ofcourse,thereisnoonlybestwayofcreationofеруprograms.Differenttechnologies
andparadigmsarerequiredfortheprogrammingofdifferentproblemsandtheirlevelsof
complexity.So,intheelementarycasesisquiteenoughoftheknowingofelementsof
structuralwritingofprograms.Whileforcreationofcomplexprogramprojectsisrequired
notonlytobefluentinaprogramminglanguageinratherfullvolume,butalsotohave
notionoftheprinciplesofelaborationanddebuggingofprograms,opportunitiesofboth
standardandotherlibrariesofoneortheothersoftware,etc.
Asarule,thantheproblemismorecomplex,themoretimeisrequiredformasteringof
thetoolsnecessaryforitsdecision.Inthiscontextthesoftware
(procedures/functions/globalvariables)whichispresentedinthepresentbookcontaina
numberofratherusefulandeffectivemethodsofprogrammingintheMathematica
environmentandextendsitsprogramenvironment,theygiveopportunitymoresimplyand
effectivetoprogramdifferentproblems.Thesemeansintheprocessofapplicationof
theAVZ_Packagepackageareupdated,takingintoaccountboththenewmeans,andthe
optimizationofalreadyexistingmeans.Inmanyproblemsofdifferentpurposethe
packageAVZ_Packageshoweditselfasarathereffectivetoolkit.Thepackageonthe
freewareconditionsisattachedtothepresentbook[48].
Chapter1.Additionalmeansininteractivemodeofthe
Mathematicasystem
FurtherwewilldistinguishtwomainoperatingmodeswithMathematica–interactive
andprogram.Underthefirstmodestep-by-stepperformancewithaMathematica
document,i.e.fromaninputIn[n]uptooutputOut[n]willbeunderstoodwhileunder
theprogrammodetheoperatingwithinablockoramoduleisunderstood.Inthepresent
chaptersomeadditionalmeansratherusefulatworkwithMathematicaininteractivemode
areconsidered.Inthecourseofoperatingininteractivemodeinmanycasesthereisaneed
ofuseofearliercalculatedexpressionsinthepreviousIn-paragraphs.Forthispurpose
the%koperator{%,%%,%%…%%(ktimes)}serveswhichdefinesreturnofthelast,
penultimateandkthpreviousresultofcalculationsinthecurrentsession.Inaddition,it
shouldbenotedthat%–operatorsinsystemsMathematicaandMapleareconceptually
various.Though,havingvariousrealareasofapplicabilityinMathematicaandMaple,at
thesametime%–operatorspossessboththeshortcomings,andessentialadvantages[2833].TheMathematicasupports2ratherusefulpredeterminedglobalvariables:
$Line–definesnumberofthelastInparagraphofthecurrentsession;
$HistoryLength–definesnumberofthepreviousparagraphsInandOutkeptinthecurrent
session.
Moreover,thesevariablesallowredefinitionsbysimpleassignmentofnewvalues.
For$HistoryLengthvariablevaluebydefaultistheinfinity(∞);butusingsmaller
installationsforthevariable,itispossiblesignificantlytosavethesizeofRAMrequired
forMathematicasystem.Inturn,globalvariable$Line1unlikethestandardglobal
variable$LinedeterminestotalnumberofOutparagraphsofthecurrentsession,including
resultsofcalculationoftheuserpackagesloadedintothesessionfromfilesofformats
{”cdf“,“nb”}.
In[500]:=$Line1:=Block[{a=””,c=“Out[“,k=1},For[k,k
ToString[Out[k]];If[a==c<>ToString[k]<>“]”,Return[k]]];k]
In[501]:=$Line1
Out[501]=2014
In[502]:=$Line
Out[502]=502
Theabovefragmentrepresentssourcecodeandexamplesofapplication.So,afterloading
oftheuserpackagethevaluesofvariables$Line1and$Linecandifferrathersignificantly:
thefirstdefinestotalnumberofthekeptOut–paragraphs,whilethesecond–numberof
reallyreceivedOut–paragraphsinthecurrentsessionoftheMathematica.
Inawholeseriesofcasesofworkwithlargedocumentsthereisexpediencyofdeleting
fromthecurrentsessionofearlierusedOutparagraphswiththeresultsunnecessaryinthe
future.ThisoperationisprovidedbythesimpleClearOutprocedure,whose
callClearOut[x]returnsnothingandatthesametimedeletesOutparagraphswithnumbers
determinedbyawholepositivenumberortheirlistx.Thefollowingfragmentrepresents
sourcecodeoftheprocedurewithatypicalexampleofitsapplication.Thisprocedurein
somecasesalsoprovidesallocationofadditionalmemoryinworkareaofsystemwhichin
caseoflargedocumentsisquitesignificant.
In[2520]:=ClearOut[x_/;PosIntQ[x]||PosIntListQ[x]]:=
Module[{a=Flatten[{x}],k=1},Unprotect[Out];For[k,k<=Length[a],k++,
Out[a[[k]]]=.];Protect[Out];]
In[2521]:={Out[1508],Out[1510],Out[1511],Out[1515]}
Out[2521]={42,78,2014,480}
In[2522]:=ClearOut[{1508,1510,1511,1515}]
In[2523]:={Out[1508],Out[1510],Out[1511],Out[1515]}
Out[2523]={%1508,%1510,%1511,%1515}
Atthat,callofusedfunctionPosIntQ[x]orPosIntListQ[x]returnsTrueifx–apositive
numberoralistpositivenumbersaccordingly;otherwise,Falseisreturned.These
functionsarelocatedinourpackageAVZ_Package[48];atthat,manymeansrepresented
belowalsousemeansofthispackage.
Ontheotherhand,incertaincasesofworkintheinteractivemodeaneedofreplacement
ofOutparagraphsontoothercontentsarisesthatrathersimpleReplaceOutprocedure
implements,whosesuccessfulcallReplaceOut[x,y]returnsnothing,atthesametime
carryingoutreplacementofcontentsoftheexistingOut–paragraphswhicharedetermined
byawholepositiveortheirlistx,bynewexpressionsdefinedbyay–argument.Thecall
assumesparityoffactualargumentsofxandy;otherwise,callReplaceOut[x,y]isreturned
unevaluated.ThefollowingfragmentrepresentssourcecodeofReplaceOutprocedure
withtypicalexamplesofitsusage.
In[2025]:=AgnAvzVsv=80
Out[2025]=80
In[2026]:=ReplaceOut[x_/;PosIntQ[x]||PosIntListQ[x],y___]:=
Module[{a=Flatten[{x}],b=Flatten[{y}],k=1},If[b!={},If[Length[a]!=
Length[b],Defer[ReplaceOut[x,y]],Unprotect[Out];For[k,k<=Length[a],k++,
Out[a[[k]]]=b[[k]]];Protect[Out]];,
ClearOut[x]]]In[2027]:=ReplaceOut[2025,480]
In[2028]:=Out[2025]
Out[2028]=480
In[2029]:=ReplaceOut[2025]
In[2030]:=Out[2025]
Out[2030]=%2025
Moreover,thecallReplaceOut[x]deletescontentsofOut–paragraphsthataredefinedby
argumentx,generalizingthepreviousClearOutprocedure.
DefinitionofvariablesinMathematica.Likethemajorityofprogramminglanguages
inMathematicasystemforexpressionsthenames(identifiers)areused,givingpossibility
inthefuturetoaddresstosuchnamedexpressionsontheirnames.So,ontheoperator“=”
theimmediateassignmenttooneorseveralnamesofthedemandedexpressionismade
whereasontheoperator“x:=”–thepostponedassignment.Distinctionofbothtypesof
assignmentissupposedwellknowntothereader.Fordefinitionofassignmenttypethat
hasbeenappliedtoanameasimpleenoughprocedureDefOpcanbeusedwhose
callDefOp[x]returnsthetypeinstringformatofassignmentappliedtothenamexcoded
alsoinstringformat,namely:(1)“Undefined”–anamexisn’tdefined,(2)“=”–
theimmediateassignmenthasbeenappliedtoanamex,(3)“:=”–thepostponed
assignmenthasbeenappliedtoanamex.In[2040]:=DefOp[x_/;StringQ[x]&&
SymbolQ[x]||
SymbolQ[ToExpression[x]],y___]:=Module[{a=ToString[Definition[x]],b={y},c,
d},If[a==“Null”,Return[“Undefined”],c[h_]:=StringTake[a,
{Flatten[StringPosition[a,h]][[2]]+1,–1}]];If[SuffPref[a,x<>”=“,1],d=“=”,d=
“:=”];If[b!={}&&!HowAct[y],y=c[d]];d]In[2041]:=v=78;g=66;s:=46;Kr=
18;Art:=25;Res:=a+b+c;
In[2042]:=Map[DefOp,{“v”,“g”,“s”,“Kr”,“Art”,“Res”,“Avz”}]Out[2042]=
{“=”,“=”,“:=”,“=”,“:=”,“:=”,“Undefined”}
In[2043]:=Clear[y];{DefOp[“Art”,y],y}
Out[2043]={“:=”,“25”}
In[2044]:=Clear[y];{DefOp[“Res”,y],y}
Out[2044]={“:=”,“a+b+c”}
In[2945]:=Map[DefOpt,{“Kr”,“Res”}]
Out[2045]={”Kr=18“,“Res:=a+b+c”}
WhilecallDefOp[x,y]throughoptionalsecondargumenty–anundefinedvariable–
returnsanexpressionappropriatedtoanamex.Thevaluewhichhasbeenassignedtoa
variablexremainsassociatedwithituntilitsremovalon“x=.“,oronthefunctionsClear,
ClearAll,Remove,oritsredefinition.Thefragmentaboverepresentssourcecodeofthe
procedurewithexamples.ForevaluationofassignmentstheMath–languagehasDefinition
functionwhosecallDefinition[x]returnsalldefinitionsascribedtoanamexalongwith
ourDefOptprocedure(seefragmentabove)whichisconsideredinthepresentbookbelow.
Alongwiththisprocedurealsoothermeansofreturnofdefinitionsareconsidered.
Inanumberofcasesarisesanecessityofcleaningofvariablesofthecurrentsessionfrom
thevaluesreceivedasaresultofdynamicgeneration.Forthispurposeitispossibletouse
themechanismconsistinginaccumulationinalistofvaluesofvariableswhichshouldbe
removedfromthecurrentsessionsubsequently,orbeclearedfromthevaluesand
attributes.ForthispurposecanbeusedafunctionwhosecallClearValues[w]returnsthe
emptylist,atthesametimedeletingallvariableshavingvaluesfromthelistwfromthe
currentsession;whereasthecallClearValues[w,y]withthesecondoptionalargumenty
–anyexpression–returnstheemptylist,howeversuchvariablesareonlyclearedofvalues
andattributeswithoutremovalfromthecurrentsession.Thefollowingfragment
representssourcecodeoftheClearValuesfunctionalongwithtypicalexamplesofits
usage.
In[2070]:=ClearValues[x_/;ListQ[x],y___]:=Select[Map[If[{y}=={},Remove,
ClearAll],Select[Names[“`*”],MemberQ[x,ToExpression[#]]&]],#!=“Null”&]
In[2071]:={a=42,b=80,c:=75,d=480,h5:=67,Kr=18,Art=x+Sin[y]}
Out[2071]={42,78,Null,460,Null,17,78+Sin[2013]}
In[2072]:=ClearValues[{42,78,75,480,67,18,x+Sin[y]}]
Out[2072]={}
In[2073]:=Names[“`*”]
Out[2073]={”ClearValues“,“Avz“,“g“,“Res“,“s”}
In[2075]:={a=42,b=78,c:=75,d=460,h5:=66,Kr=17,Art=x+Sin[y]}
Out[2075]={42,75,Null,450,Null,16,x+Sin[y]}
In[2076]:=ClearValues[{42,78,75,460,66,17,x+Sin[y]},78]Out[2076]={}
In[2077]:=Names[“`*”]
Out[2077]={”a“,“Art“,“b“,“c“,“ClearValues“,“d“,“h5“,“Kr”}In[2210]:=
VarsValues[x_/;ListQ[x]]:=Select[Names[“`*”],
MemberQ[x,ToExpression[#]]&]In[2211]:={a=42,b=78,c:=75,d=480,h5:=
67,Kr=18,Art=x+Sin[y]}:In[2212]:=VarsValues[{42,78,75,480,67,18,x+
Sin[y]}]
Out[2212]={”a“,“Art“,“b“,“c“,“d“,“h5“,“Kr”}
InthesecondpartofthefragmenttheVarsValuesfunctionisrepresented,whose
callVarsValues[x]returnsthelistofvariablesinstringformatwhichhavevaluesfroma
listx.Bothfunctionsrepresentacertaininterestduringtheworkininteractivemodeofthe
currentsession.Therecommendationsaboutuseofthesefunctionscanbefoundinour
book[33].
Insomecasesonthebasisofacertainvalueisrequiredtodeterminenamestowhichin
thecurrentsessionthisvaluewasascribed.Thegivenproblemissolvedbytheprocedure
whosecallNvalue[x]returnsthelistofnamesinstringformatwithapresetvaluex.At
that,theproceduregivesonlythoseglobalvariableswhosevalueshavebeenreceivedin
thecurrentsessioninInparagraphs.Intheabsenceofsuchnamestheprocedurecall
returnstheemptylist,i.e.{}.Thefollowingfragmentpresentssourcecodeandexample
ofusageoftheNvalueprocedure.
In[2725]:=Nvalue[x_]:=Module[{a={},b=Names[“`*”],k=1},
For[k,k<=Length[b],k++,If[ToExpression[b[[k]]]==x,AppendTo[a,b[[k]]],
Next[]]];Select[a,!SuffPref[#,“Global`”,1]&]
In[2726]:={Ag,Av,Art,Kr,V,$Ar,Vs,$Kr,G}={72,67,18,25,78,480,Null,2014,
a*b};Map[Nvalue,{72,67,18,25,78,480,Null,2014,a*b}]
Out[2726]={{”Ag”},{”Av”},{”Art”},{”Kr”},{”V”},{“$Ar”},{”Vs”},{“$Kr”},{”G”}}
TheNvalue1procedureisanextensionoffunctionalityoftheaboveNvalueprocedure.
ThecallNvalue1[x]returnsthelistofnamesofvariablesinthestringformattowhichin
thecurrentsessionavaluexhasbeenascribed.Inthenextfragmentthesourcecode
ofNvalue1withexamplesarepresented.
In[4334]:=Nvalue1[x_]:=Module[{a={},b=Select[Names[“*”],StringFreeQ[#,
“$”]&],c,k=1},While[k<=Length[b],c=ToExpression[“Attributes[”<>
ToString1[b[[k]]]<>“]”];If[!MemberQ[c,Protected],AppendTo[a,b[[k]]],Null];
k++];
Select[a,ToExpression[#]===x&]]In[4335]:={x,y,z,t,h,g,w,s}={45,78,25,18,
18,18,18,18};Nvalue1[18]Out[4335]={”Art“,“g“,“h“,“s“,“t“,“u“,“w”}
Meanwhile,theNvalue1hasnotquitesatisfactorytimecharacteristicsasitsalgorithmis
basedontheanalysisofallactiveobjectsofboththeuserones,andthesystemones.
Fordefinitionofthevaluesascribedtovariables,theprocedureWhatValueisquiteuseful
whosecallWhatValue[x]returnsvalueascribedtoavariablex;onanundefinedvariablex
thelistofformat{”Undefined“,x}isreturnedwhileonasystemvariablexthelistof
format{”System“,x},andonalocalvariablexthelistofformat{”Local“,x},isreturned.
ThefollowingfragmentrepresentssourcecodeoftheWhatValuealongwithexamplesof
itsusage.In[2844]:=WhatValue[x_]:=If[SystemQ[x],{“System”,x},
If[!SameQ[Definition2[ToString[x]][[1]],ToString[x]],{“Local”,x},{“Undefined”,
x}]]In[2845]:=Ag[x_]:=Module[{},x^2];Sv[x_]:=Block[{a},a+x];F[x_,y_]:=x*y
In[2846]:=Map[WhatValue,{480+78*#&,hg,Sin,Ag,Sv,78,a*b,F,Gs}]
Out[2846]={{”Undefined“,480+78#1&},{”Undefined“,hg},{”System“,Sin},
{”Local“,Ag},{”Local“,Sv},{”Undefined“,78},{”Undefined“,a*b},{”Local“,F},
{”Undefined“,Gs}}
In[2847]:=M=Module[{avz},avz];WhatValue[M]
Out[2847]={”Local“,avz$50551}
ThecallClear[x1,…,xn]ofthestandardfunctionclearssymbols{x1,…,xn},excepting
symbolswithProtected-attribute.AsausefulgeneralizationofthefunctionsClear
andClearAlltheprocedureClear1canbeconsideredwhosecallClear1[h,“x1”,…,“xn”]
returnsNull,i.e.nothing,clearingatconditionh=1thesymbols{x1,x2,…,xn}with
savingofalltheirattributesandoptionswhileath=2,clearingsymbols{x1,x2,…,xn}as
fromexpressionsascribedtothem,andfromallattributesandoptions.Thefragment
belowrepresentssourcecodeofClear1alongwithexamplesofitsusage.
In[2958]:=Clear1[x_/;MemberQ[{1,2},x],y___]:=Module[{a={y},b,c,d,k=
1},If[y==={},Null,For[k,k<=Length[a],k++,b=a[[k]];d=
Quiet[ToExpression[“Attributes[”<>ToString1[b]<>“]”]];
ToExpression[“Quiet[ClearAttributes[”<>ToString1[b]<>“,”<>ToString[d]<>
“]”<>“;Clear”<>If[x==1,””,“All”]<>“[”<>
ToString1[b]<>“]]”]];If[x==2,Null,Quiet[Check[ToExpression[“SetAttributes[”
<>ToString1[b]<>“,”<>ToString[d]<>“]”],$Failed]]]]]In[2959]:=S[x_]:=x^2;
SetAttributes[S,{Listable,Protected}];Clear[“S”];
Clear::wrsym:SymbolSisProtected.>>
In[2960]:=Clear1[1,S]
In[2961]:=Definition[S]
Out[2961]=Attributes[S]={Listable,Protected}
In[2962]:=Clear1[2,S]
In[2963]:=Definition[S]
Out[2963]=Null
AsarathersimpleandusefultooltheUnDefprocedureserves,whosecallUnDef[x]
returnsTrueifasymbolxisn’tdefined,andFalseotherwise.WhilecallUnDef[x,y]with
thesecondoptionalargument–anundefinedvariable–returnsHead1[x]valuethroughy,
whereHead1isanusefulgeneralizationofstandardfunctionHeadconsideredbelow.At
that,inanumberofcasesofproceduralprogrammingtheUnDefappearsasaquiteuseful
toolalso.ThefragmentrepresentssourcecodeofUnDefwithexamplesofitsusage.
In[2490]:=UnDef[x_,y___]:=Module[{a={y},b=Quiet[Check[Head1[x],True]]},
If[a!={}&&!HowAct[y],y=b];If[b===“SetDelayed||TagSetDelayed”,True,
False]]In[2491]:=x=78;y={a,b};z=a+b;Map[UnDef,{t,h,x,y,z,760}]
Out[2491]={True,True,False,False,False,False}
In[2492]:=A[x_/;UnDef[x]]:=Block[{a},a=480;a];y:=2014;{A[y],A[78]}
Out[2492]={A[2014],A[78]}
In[2493]:=L={a,b,c,d,h,g,p,v,w};Select[L,UnDef[#]&]Out[2493]={a,b,c,d,
p,v,w}
In[2494]:=M[x_]:=x;{UnDef[M,t],t}
Out[2494]={False,“Function”}
RightthereitisappropriatetonotethatonexamplesofUnDef1,UnDef2,UnDef3–
theUnDefproceduremodifications–basicdistinctionbetweenproceduresofthe
types”Module”and”Block”isillustrated[28-33].Thereforethetypeofprocedureshould
bechosenrathercircumspectly,givingacertainprioritytoproceduresofModule-type.In
addition,astheenclosedprocedurestheproceduresofModule–typeareused,asarule.
Inanumberofcasesexistsaneedofdefinitionofacontextofanarbitrarysymbol.This
problemissolvedbyasimpleenoughprocedure,whosecallAffiliate[x]returnsthe
contextforanarbitrarysymbolxgiveninthestringformatwhereas”Undefined”is
returnedonasymbol,completelyundefiniteforthecurrentsession.Atthat,
under”completelyundefinite”isunderstoodasaconcreteexpression,andasymbolforthe
firsttimeusedinthecurrentsession.Thefragmentbelowrepresentssourcecodeofthe
givenprocedureandexamplesofitsusage,includingexamplesexplainingtheessenceof
theconcept”completelyundefinite“.
In[80]:=Affiliate[x_/;StringQ[x]]:=Module[{a=Quiet[Context[x]]},If[ToString[a]
===“Context[”<>x<>“]”,“Undefined”,
If[MemberQ[Contexts[],a]&&ToString[Quiet[DefFunc[x]]]]==“Null”||
Attributes[x]==={Temporary},“Undefined”,a]]]In[81]:=G=67;Map[Affiliate,
{“ProcQ1”,“Sin”,“G”,“Z”,“Affiliate”}]Out[81]={”AladjevProcedures`”,
“System`”,“Global`”,“Undefined“,
“AladjevProcedures`”}
In[82]:={V,G=72,67};Map[Affiliate,{“V”,“G”,“80”,“Sin[18]”,“Q”,“Map”}]
Out[82]={”Undefined“,“Global`”,“Undefined“,“Undefined“,“Undefined“,
“System`”}
ThecallWhatObj[x]ofaquitesimpleprocedurereturnsvaluedependingonlocationof
axsymbolactivatedinthecurrentsession,namely:”System”asystemfunction;”CS”–a
symbolwhosedefinitionhasbeendefinedinthecurrentsession;”Undefined”–an
undefinitesymbol;”Context’”–acontextdefiningapackageloadedintothecurrent
sessionandcontainingdefinitionofxsymbol;ifxhasatypeotherthanSymbol,the
procedurecallisreturnedasunevaluated.Thefollowingfragmentrepresentssourcecode
ofWhatObjprocedurealongwithexamplesofitsusage.
In[2139]:=WhatObj[x_/;SymbolQ[x]]:=Module[{a=Quiet[Context[x]],t},If[a
===“System`”,“System”,If[a===“Global`”,If[MemberQ[{$Failed,“Undefined”},
PureDefinition[x]],“Undefined”,“CS”],a]]]
In[2140]:=w[x_]:=Block[{},x];Map[WhatObj,{Sin,a/b,ProcQ,t78,h6,w}]
Out[2140]={”System“,WhatObj[a/b],“AladjevProcedures`”,“Undefined“,
“Undefined“,“CS”}
Fortestingofsymbolstowhichexpressionsareascribed,2simplefunctionsHowAct
andSymbolQaredefined.Thefirstofthemcorrectlyteststhefactofdefinitenessofa
variableinthecurrentsession,howeveronlocalvariablesofproceduresthecall
ofHowActreturnsTrueirrespectiveofexistenceforthemofvalues.Ontheotherhand,on
undefinitelocalvariablesofblockstheHowActreturnsFalse.ThecallSymbolQ[x]of
simplethoughratherusefulfunctionreturnsTrueifxisasymbol,andFalseotherwise.
Functionisusedinanumberoftoolspresentedinthepresentbook.Thefollowing
fragmentrepresentssourcecodesofbothfunctionswithexamplesoftheirusage.
In[2020]:=HowAct[x_]:=If[Quiet[Check[ToString[Definition[x]],True]]===
“Null”,False,If[Quiet[ToString[Definition[x]]]===“Attributes[”<>ToString[x]<>
“]={Temporary}“,False,True]]
In[2021]:=SymbolQ[x_]:=!SameQ[Quiet[Check[ToExpression[“Attributes[”<>
ToString[x]<>“]”],$Failed]],$Failed]
In[2022]:=Map[HowAct,{80,IAN,“RANS”,Cos,Args,TestArgsTypes,Label,
HowAct,a+b,Agn}]
Out[2022]={True,False,True,True,True,True,True,True,True,False}
In[2023]:=Map[SymbolQ,{80,IAN,“RANS”,Cos,Args,Label,HowAct}]
Out[2023]={False,True,True,True,True,True,True,True}
IncertaincasestheSymbolQ1function,beingofamodificationoffunctionSymbolQcan
beuseful,whosecallSymbolQ1[x]returnsTrueifxisasinglesymbol,andFalseotherwise
[33].In[33]certainfeaturesofusageofHowActfortestingofdefinitenessoflocal
variablesofprocedurescanbefound.Inanumberofcasesexistsaneedofremovalfrom
thecurrentsessionofacertainactiveobjecthavingtheappropriatedvaluewithpossibility
ofitssubsequentrestorationinthecurrentorothersession.Thegivenproblemissolved
bythefunctionwhosecallActRemObj[x,y]dependingonavalue{“Act”,“Rem”}ofthe
secondactualargumentdeletesanobjectgivenbyhisnameinstringformatfromthe
currentsessionoractivatesitinthecurrentorothersessionrespectively.Thefragment
belowrepresentssourcecodeoftheActRemObjprocedurealongwithexamplesofits
usage.
In[647]:=ActRemObj[x_/;StringQ[x],y_/;MemberQ[{“Act”,“Rem”},y]]:=
Module[{a=$HomeDirectory<>“\”<>x<>“.$ArtKr$”,b,c=
ToString[Definition4[x]]},If[c===“$Failed”,$Failed,If[HowAct[x]&&y==
“Rem”,b=OpenWrite[a];WriteString[b,c];Close[b];ClearAllAttributes[x];
Remove[x];“Remove”,If[!HowAct[x]&&y==“Act”,If[FileExistsQ[a],
b=OpenRead[a];Read[b];Close[b];DeleteFile[a];“Activate”,
Return[Defer[ActRemObj[x,y]]]]]]]]In[648]:=F:={72,67,47,18,25};
SetAttributes[F,Protected];Definition[F]Out[648]=Attributes[F]={Protected}
F:={72,67,47,18,25}
In[649]:=ActRemObj[“F”,“Rem”];
Out[649]=“Remove”
In[650]=Definition[F]
Out[650]=Null
In[651]:=ActRemObj[“F”,“Act”];
Out[651]=“Activate”
In[652]=Definition[F]
Out[652]=Attributes[F]={Protected}
F:={72,67,47,18,25}
In[653]:=A[x_]:=Module[{a=480},x+a];A[x_,y_]:=Module[{a=80},x+y+a]
In[654]:={A[100],A[100,200]}
Out[654]={580,380}
In[655]:=ActRemObj[“A”,“Rem”];Definition[A]
Out[655]=Null
In[656]:=ActRemObj[“A”,“Act”];{A[100],A[100,200]}
Out[656]={590,380}
Successfulremovalofanobjectfromthecurrentsessionreturns“Remove”whereasits
restorationinthecurrentsessionreturns”Activate“.Ifadatafilecontainingdefinitionofa
removedobjectx,wasn’tfoundinsystemcatalog$HomeDirectory,thecall
ofActRemObjprocedureisreturnedunevaluated;onaninadmissibleargumentxthe
callActRemObj[x,y]returns$Failed.
SystemMaplehasaratherusefulrestartcommandwhichcausestheMaplekerneltoclear
itsinternalmemorysothatsystemMapleactsalmostasifjuststarted.While
theMathematicasystemhasnosimilarmeansininteractivemode.Thenextprocedureto
acertainextentcompensatesforthisdeficiency.ThecallRestart[]returnsnothing,deleting
fromthecurrentsessionallobjectsdefinedinit.Moreover,fromthegivenlistare
excludedtheobjectswhosedefinitionsareinthedownloadedpackages.Whilethe
callRestart[x]withoptionalargumentx–acontextortheirlistdefiningtheuserpackages
thathavebeenloadedinthecurrentsession–alsoreturnsnothing,additionallydeleting
fromthecurrentsessionallobjectswhosedefinitionsarecontainedinthementioneduser
packages.ThefollowingfragmentrepresentssourcecodeoftheRestartprocedurealong
withexamplesofitsapplication.
In[2450]:=Restart[x___]:=Module[{},Map[{Quiet[ClearAttributes[#,Protected]],
Quiet[Remove[#]]}&,Names[“`*”]];If[{x}!={},Quiet[Map[Remove[#<>“*”]&,
Flatten[{x}]]]]]
In[2451]:=F:={72,67,47,18,25};SetAttributes[F,Protected];Sv=47;a:=6;
A[x_]:=Module[{a=480},x+a];A[x_,y_]:=Module[{a=80},x*y*a];
In[2452]:=Restart[“AladjevProcedures`”]
In[2453]:=Map[Definition,{F,A,Map13,HowAct,Sv,a,ActUcontexts}]
Out[2453]={Null,Null,Null,Null,Null,Null,Null]}
Moreover,thesystemobjectsarenotaffectedbytheRestart.Inanumberofcasesthe
functionseemsaratheruseful,allowingtosubstantiallyrestoreaninitialstateofthe
currentsessionandtosaveinternalmemoryofsystemtoo.
Meansofworkwithsequentialstructures.Sequencesofexpressions(simplysequences)in
theenvironmentofmanylanguagesareformedonthebasisofthecommaoperator“,”and
formacertainbasefordefinitionofmanytypesofdata(inquiriesof
procedures,lists,sets,indexes,etc.).Atthat,inMathematicasystemthegivenstructureasan
independentoneisabsent,andinsteadofittheliststructureprotrudes;someprogramming
languagesadheretothesameconcept.Inthiscontextanumberofsimpleenoughmeans
hasbeencreatedthatensureoperatingwiththeobjectSeq[x]definingasequenceof
elementsx.So,theprocedurecallSeqToList[x]providesconvertingofSeq–objectxinto
thelist,theprocedurecallListToSeq[x]providesconvertingofalistxintoSeq–object,the
procedurecallSeqIns[x,y,z]returnstheresultofinsertinginSeq–objectxofanarbitrary
elementy(list,Seq–object,expression,etc.)accordingtothegivenpositionz(z<=0
–beforex,z>=Length[x]–afterx,differently–afteraz–positioninx),theprocedure
callSeqToString[a,b,…]returnsthelistofargumentsinstringformat,whereasthe
callSeqUnion[x,y,…]returnsresultofmergeofanarbitrarynumberofsequences.Means
formanipulatingwithSeq-objectscanberatherwidelyexpanded,providingtheuserwith
ratherusefulprogramtools.Inacertainrelationthesetoolsallowtosolvetheproblemof
compatibilitywithothertools,forexample,withtheMaplesystem[28-33].
Meanwhile,theMathematicasystemprovidesthefunctionSequence[a,…]thatdefinesa
sequenceofargumentswhichareautomaticallytransferredtoablock,functionormodule.
InthiscontextthecallSequenceQ[s]providestestingoftheobjectsthatarecreatedonthe
basisoftheSequencefunctionreturningTrueifas–objectisdefinedbythisfunction,
andFalseotherwise;moreover,thenameofs–objectiscodedinstringformat[33].Onthe
basisofthestandardSequencefunctionitispossibletocreatequitesimpletoolsensuring
workingwithsequentialstructuressimilarlytotheMaplesystem;thesefunctionsalong
withtheconsideredonesin[28-33]areratherusefulinworkwithobjectsof
type”sequence“,whosestructureisn’tsupportedbytheMathematicaandforworkwith
whichsystemhasnostandardmeans.ThecallSequence[x1,x2,…,xn]ofthestandard
functiondefinesasequenceofactualargumentsxj(j=1..n),transferredtoafunction.
Meanwhile,withobjectsoftype”sequence”theMathematicasystemcanworkmediately,
inparticular,onthebasisoftheliststructures.Inthisregardforexpansionof
standardSequencefunctionontoliststructurestheSequencesprocedureisdefined,whose
callSequences[x]providesinsertinafunctionofargumentsxgivenbyasequenceora
list;asasimplifiedvariantofSequencestheSqfunctionserves.Thefollowingfragment
representssourcecodesoffunctionSqalongwiththeSequencesprocedure,including
theirapplications.
In[3495]:=Sequences[x__]:=Module[{a=Flatten[{x}],b,c},
b=“Sequence[”<>ToString[a]<>“]”;a=Flatten[StringPosition[b,{”{“,“}”}]];
ToExpression[StringReplace[b,{StringTake[b,{a[[1]],a[[1]]}]–>””,StringTake[b,
{a[[–1]],a[[–1]]}]–>””}]]]
In[3496]:={F[Sequence[{x,y,z}]],F[Sequences[{x,y,z}]],F[Sequences[x,y,z]]}
Out[3496]={F[{x,y,z}],F[x,y,z],F[x,y,z]}
In[3497]:=Sq[x_List]:=ToExpression[“Sequence[”<>
StringTake[ToString1[x],{2,–2}]<>“]”]In[3498]:=Plus[Sq[{72,66,56,47,25,18}]]
Out[3498]=284
In[3499]:=G[a,b,c,Sequences[x,y,z]]
Out[3499]=G[a,b,c,x,y,z]
Atworkwithsequentialstructuresaratherusefulisaprocedure,providingconvertingof
stringsofaspecialformatintolists,andviceversa.ThecallListStrList[x]onalistx={a,
b,…}returnsastringsoftheformat”ahbh…”,whilex=ListStrList[s]whereh=
FromCharacterCode[2].IncaseofabsenceinasstringofhsymbolthecallListStrList[s]
returnsthestrings.Fragmentrepresentssourcecodeoftheprocedurealongwithexamples
itsusage.In[2604]:=ListStrList[x_/;StringQ[x]||ListQ[x]]:=
Module[{a=FromCharacterCode[2]},If[StringQ[x]&&!StringFreeQ[x,a],
Map[ToExpression,StringSplit[x,a]],If[ListQ[x],StringTake[StringJoin[
Mapp[StringJoin,Map[ToString1,x],a]],{1,–2}],x]]]
In[2605]:=L=ListStrList[{Avz,72,Agn,67,Art,25,Kr,18,Vsv,47}]Out[2605]=
“Avz72Agn67Art25Kr18Vsv47”
In[2606]:=ListStrList[ListStrList[{Avz,72,Agn,67,Art,25,Kr,18,Vsv,47}]]
Out[2606]={Avz,72,Agn,67,Art,25,Kr,18,Vsv,47}
Chapter2.Additionalmeansofprocessingofexpressionsin
theMathematicasoftware
Anumberofusefulmeansofprocessingoftheexpressionssupplementingstandardmeans
ofMathematicasystemispresentedinthepresentchapter.Analogouslytothemost
softwaresystemstheMathematicaunderstandseverythingwithwhatitmanipulates
as”expression”(graphics,lists,formulas,strings,modules,functions,numbersofvarious
type,etc.).Andalthoughalltheseexpressionsatfirstsightrathersignificantly
differ,Mathematicarepresentstheminso–calledfullformat.Andonlythepostponed
assignment”:=”hasnofullformat.Forthepurposeofdefinitionofheading(thetype
definingit)ofanexpressionthestandardHeadfunctionisused,whosecallHead[expr]
returnstheheadingofanexpressionexpr,forexample:
In[6]:=Map[Head,{Map,Sin,80,a+b,Function[{x},x],G[x],S[6],x*y,x^y}]
Out[6]={Symbol,Symbol,Integer,Plus,Function,G,S,Times,Power}
Formoreexactdefinitionofheadingswecreatedanusefulmodificationofthe
standardHeadfunctionintheformoftheHead1procedureexpandingitsopportunities,for
example,itconcernstestingofoperationsofpostponedcalculationswhenonthemthe
valuesSetDelayed||TagSetDelayed,blocks,functions,modulesarereturned.The
callHead1[x]returnstheheadingofanexpressionxinthecontext
{Block,Function,Module,PureFunction,System,
SetDelayed||TagSetDelayed,Symbol,Head[x]}.Thefragmentrepresentssourcecodeof
theHead1procedurewithexamplesofitsapplicationcomparativelywiththeHead
functionasitisillustratedbyexamplesofthenextfragment,onwhichfunctional
distinctionsofbothmeansareratherevident.
In[2160]:=Head1[x_]:=Module[{a,b,c=Quiet[Check[Attributes[x],{}]]},
If[Quiet[SystemQ[x]],OptRes[Head1,System],If[c!={},ClearAllAttributes[x]];b=
Quiet[StringSplit[ToString[Definition[x]],“\n\n”]];a=If[!SameQ[b,{}]&&b[[–1]]
==“Null”,If[Head[x]==Symbol,Symbol,SetDelayed||TagSetDelayed],
If[PureFuncQ[x],PureFunction,If[Quiet[Check[FunctionQ[x],False]],Function,
If[BlockQ[x],Block,If[BlockModQ[x],Module,Head[x]]]]]];{OptRes[Head1,a],
Quiet[SetAttributes[x,c]]}[[1]]]]In[2161]:=G:=S;Z[x_]:=Block[{},x];F[x_]:=x;
Map[Head,{ProcQ,Sin,6,a+b,#&,G,Z,Function[{x},x],x*y,x^y,F}]
Out[2161]={Symbol,Symbol,Integer,Plus,Function,Symbol,Symbol,Function,
Times,Power,Symbol}
In[2162]:=Map[Head1,{ProcQ,Sin,6,a+b,#&,G,Z,Function[{x},x],x*y,x^y,
F}]
Out[2162]={Module,System,Integer,Plus,PureFunction,Symbol,Block,PureFunction,
Times,Power,Function}
So,theHead1procedurehasaquitecertainmeaningformoreexact(relativetosystem
standard)classificationofexpressionsaccordingtotheirheadings.Onmanyexpressions
thecallsofHead1procedureandHeadfunctionareidenticalwhereasonanumbertheir
callssignificantlydiffer.Theconceptofexpressionistheimportantunifyingprinciplein
thesystemhavingidenticalinternalstructurethatallowstoconfinearathersmallamount
ofthebasicoperations.Meanwhile,despiteidenticalbasicstructureofexpressions,the
Mathematicasystemprovidesasetofvariousfunctionsforworkbothwithanexpression
ingeneral,andwithitsseparatecomponents.
Meansoftestingofcorrectnessofexpressions.Mathematicahasanumberofthemeans
providingtestingofcorrectnessofsyntaxofexpressionsamongwhichonlytwofunctions
areavailabletotheuser,namely:
SyntaxQ[“x“]–returnsTrue,ifx–asyntacticcorrectexpression;otherwiseFalseis
returned;
SyntaxLength[“x”]–returnsthenumberpofsymbols,sincethebeginningofa
string“x”thatdefinessyntacticcorrectexpressionStringTake[“x“,{1,p}];atthat,in
casep>StringLength[“x“]thesystemdeclaresthatwholestring“x”iscorrect,demanding
continuation.
Inouropinion,itisn’tveryconvenientlyineventofsoftwareprocessingofexpressions.
ThereforeextensionsintheformoftheSyntaxQ1functionandSyntaxLength1procedure
whosesourcecodesalongwithexamplesoftheirapplicationarerepresentedbelow.
In[2029]:=SyntaxQ1[x_/;StringQ[x]]:=If[Quiet[ToExpression[x]]===$Failed,
False,True]
In[2030]:=Map[SyntaxQ1,{“(a+b/”,“d[a[1]]+b[2]”}]
Out[2030]={False,True}
In[2031]:=SyntaxLength1[x_/;StringQ[x],y___]:=Module[{a=””,b=1,d,h={},
c=StringLength[x]},
While[b<=c,d=Quiet[ToExpression[a=a<>StringTake[x,{b,b}]]];If[!SameQ[d,
$Failed],h=Append[h,StringTrim[a]]];b++];h=DeleteDuplicates[h];If[{y}!=
{}&&!HowAct[{y}[[1]]],{y}={h}];
If[h=={},0,StringLength[h[[–1]]]]]
In[2437]:={SyntaxLength1[“d[a[1]]+b[2]”,g],g}
Out[2437]={14,{”d“,“d[a[1]]“,“d[a[1]]+b“,“d[a[1]]+b[2]”}}
In[2438]:=SyntaxLength1[“d[a[1]]+b[2]”]
Out[2438]=14
ThecallSyntaxLength1[x]returnsthemaximumnumberpofpositioninastringxsuch
thatToExpression[StringTake[x,{1,p}]]–asyntacticcorrectexpression,otherwise0is
returned;thecallSyntaxLength1[x,y]throughthesecondoptionalargumenty–an
undefinitevariable–additionallyreturnsthelistofsubstringsofastringxrepresenting
correctexpressions.
Meansofprocessingofexpressionsattheleveloftheircomponents.Meansofthisgroup
providequiteeffectivedifferentiatedprocessingofexpressions.Thecombinedsymbolical
architectureofMathematicagivesthepossibilityofdirectgeneralizationoftheelementorientedlistoperationsontoarbitraryexpressions,supportingoperationsbothonseparate
terms,andonsetsoftermsatthegivenlevelsintreesofexpressions.Withoutgoinginto
detailsintoallmeanssupportingworkwithcomponentsofexpressions,wewillgiveonly
themainfromthemthathavebeencomplementedbyourmeans.Whereaswithmore
detaileddescriptionofstandardmeansofthisgroup,includingadmissibleformatsof
coding,itispossibletogetacquaintedorintheHelp,orinthecorrespondingliteratureon
theMathematicasystem,forexample,inworks[51,52,60,66,71].
ThecallVariables[p]ofstandardfunctionreturnsthelistofallindependentvariablesofa
polynomialp,whileitsapplicationtoanarbitraryexpressionhascertainlimitations.
Meanwhileforreceivingallindependentvariablesofanexpressionxitisquitepossibleto
usequitesimplefunctionwhosecallUnDefVars[x]returnsthelistofallindependent
variablesofanexpressionx.UnliketheUnDefVarsfunction,thecallUnDefVars1[x]
returnsthelistofallindependentvariablesinstringformatofanexpressionx.Source
codesofbothfunctionswithexamplesoftheirapplicationaregivenbelowinthe
comparativecontextwithVariablesfunction.Insomecasesthementionedfunctionshave
certainpreferencesrelativetostandardVariablesfunction.
In[2024]:=UnDefVars[x_]:=Select[OP[x],Quiet[ToString[Definition[#]]]==“Null”
&]
In[2025]:=UnDefVars[(x^2–y^2)/(Sin[x]+Cos[y])+a*Log[x+y+z–G[h,t]]]
Out[2025]={a,G,h,t,x,y,z}
In[2026]:=Variables[(x^2–y^2)/(Sin[x]+Cos[y])+a*Log[x+y+z–G[h,t]]]
Out[2026]={a,x,y,Cos[y],Log[x+y+z–G[h,t]],Sin[x]}
In[2027]:=UnDefVars1[x_]:=Select[ExtrVarsOfStr[ToString[x],2],!SystemQ[#]&]
In[2028]:=Map[UnDefVars1,{a+b,a*Sin[x]*Cos[y],{a,b},a*F[h,g,s]+H}]
Out[2028]={{”a“,“b”},{”a“,“x“,“y”},{”a“,“b”},{”a“,“F“,“g“,“h“,“s”}}
ThecallReplace[x,r{,w}]ofstandardfunctionreturnsresultofapplicationofarulerof
theforma→borthelistofsuchrulesfortransformationofanexpressionxasawhole;
applicationofthe3rdoptionalargumentwdefinesapplicationofrulesrtopartsofw–level
ofanexpressionx.Meanwhile,thestandardReplacefunctionhasanumberofrestrictions
somefromwhichtheprocedureconsiderablyobviates,whosecallReplace1[x,r]returns
theresultofapplicationofrulesrtoallorselectiveindependentvariablesofan
expressionx.IncaseofdetectionbytheprocedureReplace1ofemptyrulestheappropriate
messageisprintedwiththeindicationofthelistofthoserulesrwhichwereempty,i.e.
whoseleftpartsaren’tenteredintothelistofindependentvariablesofanexpressionx.
FragmentbelowrepresentssourcecodeofReplace1withexamplesofitsapplication;at
that,comparisonwithresultofapplicationoftheReplacefunctiononthesameexpression
isgiven.
In[2052]:=Replace1[x_,y_/;ListQ[y]&&DeleteDuplicates[Map[Head,y]]==
{Rule}||Head[y]==Rule]:=Module[{a=x//FullForm//ToString,b=UnDefVars[x],
c,p,l,h={},r,k=1,d=ToStringRule[DeleteDuplicates[Flatten[{y}]]]},p=
Mapp[RhsLhs,d,“Lhs”];c=Select[p,!MemberQ[Map[ToString,b],#]&];If[c!=
{},Print[“Rules”<>ToString[Flatten[Select[d,MemberQ[c,RhsLhs[#,“Lhs”]]&]]]
<>”arevacuous”]];While[k<=Length[d],l=RhsLhs[d[[k]],“Lhs”];r=
RhsLhs[d[[k]],“Rhs”];h=Append[h,{“[”<>l–>“[”<>r,””<>l–>””<>r,l<>
“]”–>r<>“]”}];k++];Simplify[ToExpression[StringReplace[a,Flatten[h]]]]]
In[2053]:=X=(x^2–y^2)/(Sin[x]+Cos[y])+a*Log[x+y];Replace[X,{x–>a+b,
a–>80,y–>Cos[a],z–>Log[t]}]
Out[2053]=aLog[x+y]+(x^2–y^2)/(Cos[y]+Sin[x])
In[2054]:=Replace1[X,{x–>a+b,a–>80,y–>Cos[a],z–>Log[t],t–>c+d}];Rules
{z–>(Log[t]),t–>(c+d)}arevacuous
Out[2054]=80Log[a+b+Cos[a]]+((a+b)^2–Cos[a]^2)/(Cos[Cos[a]]+Sin[a+b])
In[2055]:=Replace1[X,{x–>a+b,a–>80,y–>Cos[a]}]
Out[2055]=80Log[a+b+Cos[a]]+((a+b)^2–Cos[a]^2)/(Cos[Cos[a]]+Sin[a+b])
Incertaincasesatconversionsofexpressionsbymeansofsubstitutionsthenecessityof
convertingintostringformatoftheleftandrightpartsofrules“a→b”arises.Thegiven
problemissolvedbyrathersimpleToStringRuleprocedure,whosecallToStringRule[x]
returnstheruleorthelistofrulesx,whoseleftandrightpartshavestringformat;atthat,
itsrightpartistakeninparentheses.So,thisprocedureisusedbythe
above–presentedReplace1procedure.TheprocedureToStringRule1issimilarto
ToStringRule,buttherightpartsoftheresultisnottakenintoparentheses.Thenext
fragmentrepresentssourcecodeoftheToStringRulewithexamplesofitsusage.
In[2723]:=ToStringRule[x_/;ListQ[x]&&DeleteDuplicates[Map[Head,x]]==
{Rule}||Head[x]==Rule]:=Module[{a=Flatten[{x}],b={},c,k=1},While[k<=
Length[a],c=a[[k]];b=Append[b,ToString[RhsLhs[c,“Lhs”]]–>“(”<>
ToString[RhsLhs[c,“Rhs”]]<>“)”];k++];If[ListQ[x],b,b[[1]]]]
In[2724]:={ToStringRule[a–>b],ToStringRule[{a–>b,c–>d,m–>n}]}Out[2724]=
{”a”–>“(b)“,{”a”–>“(b)“,“c”–>“(d)“,“m”–>“(n)”}}ThecallLevel[x,n]ofstandard
functionreturnslistofallsubexpressionsofanexpressionxatlevelsfrom1ton.Asan
usefulgeneralizationoffunctionisprocedurewhosecallLevels[x,h]returnsthelistofall
subexpressionsforanexpressionxatallitspossiblelevelswhilethroughthesecond
argumenth–anindependentvariable–themaximumnumberoflevelsofexpressionxis
returned.Generallyspeaking,thefollowingdefiningrelationtakesplaceLevels[x,
h]≡Level[x,Infinity],howeverincaseoftheLevelstheprocedureadditionally
returnsmaximumlevelofanexpressionx.WhiletheprocedurecallExprOnLevels[x]
returnstheenclosedlist,whoseelementsarethelistsofsubexpressionsofanexpressionx
whicharelocatedoneachofitslevelsfromthefirsttothelast.Thefragmentbelow
representssourcecodesofbothprocedureswithexamplesoftheirapplicationina
comparativecontextwiththeLevelfunctionwiththesecondInfinity–argument.
In[2868]:=Levels[x_,h_/;ToString[Definition[h]]==“Null”]:=Module[{a={},b,k
=1},While[k
In[2869]:={Levels[(x^2–y^2)/(Sin[x]+Cos[y])+a*Log[x+y+z–G[h,t]],g],g}
Out[2869]={{a,x,y,z,–1,h,7,G[h,7],–G[h,7],x+y+z–G[h,7],Log[x+y+z–G[h,7]],
aLog[x+y+z–G[h,7]],x,2,x^2,–1,y,2,y^2,–y^2,x^2–y^2,y,Cos[y],x,Sin[x],
Cos[y]+Sin[x],–1,1/(Cos[y]+Sin[x]),(x^2–y^2)/(Cos[y]+Sin[x])},6}
In[2870]:=Level[(x^2–y^2)/(Sin[x]+Cos[y])+a*Log[x+y+z–G[h,t]],Infinity]
Out[2870]={a,x,y,z,–1,h,7,G[h,7],–G[h,7],x+y+z–G[h,7],Log[x+y+z–G[h,7]],
aLog[x+y+z–G[h,7]],x,2,x^2,–1,y,2,y^2,–y^2,x^2–y^2,y,Cos[y],x,Sin[x],
Cos[y]+Sin[x],–1,1/(Cos[y]+Sin[x]),(x^2–y^2)/(Cos[y]+Sin[x])}
In[2879]:=ExprOnLevels[x_]:=Module[{a={},k=1},While[k<=Depth[x],a=
Append[a,MinusList[Level[x,k],Level[x,k–1]]];k++];a[[1;;–2]]]
In[2880]:=X=(x^2–y^2)/(Sin[x]+Cos[y])+a*Log[x+y+z–G[h,t]];In[2880]:=
ExprOnLevels[X]
Out[2880]={{aLog[x+y+z–G[h,t]],(x^2–y^2)/(Cos[y]+Sin[x])},{a,Log[x+y+z–
G[h,t]],x^2–y^2,1/(Cos[y]+Sin[x])},{x+y+z–G[h,t],x^2,–y^2,Cos[y]+Sin[x],–1},
{x,y,z,x,2,–1,y^2,Cos[y],Sin[x],–1},{G[h,t],y,2,y,x,–1},{h,t}}
RelativetotheaboveLevelsprocedurethestandardDepthfunctiondefinesonthesame
expressionthemaximumnumberoflevelsmoreon1,namely:In[3790]:=Clear[t];
{Levels[a+b+c^2,t],t,Depth[a+b+c^2]}Out[3790]={{a,b,c,2,c^2},2,3}
ThestandardFreeQfunctionprovidestestingofentriesintoanexpressionof
subexpressionswhileasimpleFreeQ1proceduresignificantlyexpandstheFreeQ
function,providingbroadertestingofentriesintoanexpressionofsubexpressions.The
callFreeQ1[x,y]returnsTrueifanexpressionxdoesn’tcontainsubexpressionsy,
otherwiseFalseisreturned.TheFreeQ2functionexpandstheFreeQfunctionadditionally
ontothelistasthe2ndargument.Atthat,thecallFreeQ2[x,p]returnsTrueifan
expressionxdoesn’tcontainsubexpressionporsubexpressionsfromalistp,
otherwiseFalseisreturned.ThefragmentrepresentssourcecodesofFreeQ1andFreeQ1
withexamplesoftheirapplicationinacomparativecontextwiththeFreeQfunction.
In[2202]:=FreeQ1[x_,y_]:=Module[{h},Quiet[FreeQ[Subs[x,y,h=
Unique[“ArtKr”]],h]]]
In[2203]:={FreeQ1[a/Sqrt[x],Sqrt[x]],FreeQ[a/Sqrt[x],Sqrt[x]]}
Out[2203]={False,True}
In[2204]:={FreeQ1[{Sqrt[x],18,25},Sqrt[x]],FreeQ[{Sqrt[x],18,25},Sqrt[x]]}
Out[2204]={False,False}
In[2250]:=FreeQ2[x_,p_]:=If[ListQ[p],If[DeleteDuplicates[Map10[FreeQ,x,p]]
==={True},True,False],FreeQ[x,p]]
In[2251]:=L={a,b,c,d,f,g,h};{FreeQ[L,{a,d,h}],FreeQ2[L,{a,d,h}]}
Out[2251]={True,False}
In[2252]:={FreeQ[Cos[x]*Ln[x],{Sin,Ln}],FreeQ2[Cos[x]*Ln[x],{Sin,Ln}]}
Out[2252]={True,False}
UsingtheFullFormfunctionprovidingrepresentationofexpressionsinthefullformcan
bereceivedaratherusefulproceduresolvingthereplacementprobleminexpressionsof
thegivensubexpressions.ThecallReplace3[x,y,z]returnstheresultofreplacementinan
arbitraryexpressionxofallentriesofsubexpressionsyintoitontoexpressionsz;as
procedurearguments{y,z}separateexpressionsortheirlistscanbeused.Atthat,incase
ofarguments{y,z}intheformofthelist,forthemthecommonlengthdeterminedbythe
relationMin[Map[Length,{y,z}]]ischosen,allowingtoavoidthepossibleespecialand
erroneoussituations,butwiththeprintingoftheappropriatediagnosticinformationas
illustratesanexamplebelow.Thenextfragmentrepresentssourcecodeoftheprocedure
withexamplesofitsusage.
In[2062]:=Replace3[x_,y_,z_]:=Module[{a=Flatten[{y}],b=Flatten[{z}],c,t=
x,k=1},c=Min[Map[Length,{a,b}]];If[c
<>ToString1[a[[c+1;;–1]]]<>”werenotreplaced”]];For[k,k<=c,k++,t=
Subs[t,a[[k]],b[[k]]]];t]
In[2063]:=Replace3[x^2+Sqrt[1/a^2+1/a–Sin[1/a]],1/a,Cos[h]]Out[2063]=x^2+
Sqrt[1/a^2+Cos[h]–Sin[Cos[h]]]
In[2064]:=Replace3[1/(1+1/a)+Cos[1/a+Sin[1/a]]*(c+1/a)^2,1/a,F[h]+d]
Out[2064]=1/(1+d+F[h])+Cos[d+F[h]+Sin[d+F[h]]](c+d+F[h])^2In[2065]:=
Replace3[x^2+Sqrt[1/a^2+1/a–Sin[1/a]],{1/a,1/b,1/c},Cos[h]]
Subexpressions{b^(–1),c^(–1)}werenotreplaced
Out[2065]=x^2+Sqrt[1/a^2+Cos[h]–Sin[Cos[h]]]
Insomecasesexistsnecessitytoexecutetheexchangeofvaluesofvariableswiththe
correspondingexchangeofallthemattributes.So,variablesxandyhavingvalues72and67
shouldreceivevalues42and47accordinglywiththecorrespondingexchangeofalltheir
attributes.TheprocedureVarExchsolvesthegivenproblem,returningNull,i.e.nothing.
Thelistoftwonamesofvariablesinstringformatwhichexchangebyvaluesand
attributesorthenestedlistofListList–typeactsastheactualargument;anywayall
elementsofpairshavetobedefinite,otherwisethecallreturnsNullwithprintofthe
correspondingdiagnosticmessage.
Ontheotherhand,thecallRename[x,y]intheregularmodereturnsNull,i.e.nothing,
providingreplacementofanamexofsomedefinedobjectontoanameywithpreservation
ofallattributesofthisobject.Atthat,thenamexisremovedfromthecurrentsessionby
meansoffunctionRemove.Butify–argumentdefinesanameofadefinedobjectoran
undefinednamewithattributes,theprocedurecallisreturnedunevaluated.Ifthefirst
argumentxisillegalforrenaming,theprocedurecallreturnsNull,i.e.nothing;atthat,
theRenameproceduresuccessfullyprocessesalsoobjectsofthesamenameofthe
type“Block”,“Function”or“Module”.TheRename1procedureisaquiteuseful
modificationoftheaboveprocedure,beingbasedonprocedureDefinition2[33].The
callRename1[x,y]issimilartothecallRename[x,y]whereasthecallRename1[x,y,z]
withthethirdoptionalz–argument–anarbitraryexpression–performsthesamefunctions
asthecallRename1[x,y]withoutchangeofaninitialobjectx.
TheVarExch1procedureisaversionoftheaboveprocedureVarExchandisbasedon
usageoftheRenameprocedureandglobalvariables;itadmitsthesametypeoftheactual
argument,butunlikethesecondprocedurethecallVarExch1[L]incaseofdetectionof
undefiniteelementsofalistLoritssublistsisreturnedunevaluatedwithoutprintofany
diagnosticmessage.Inthefragmentbelow,thesourcecodesoftheproceduresRename,
Rename1,VarExchandVarExch1alongwithexamplesoftheirusagearerepresented.
In[2545]:=VarExch[L_List/;Length[L]==2||ListListQ[L]&&Length[L[[1]]]==2]
:=Module[{Kr,k=1},
Kr[p_List]:=Module[{a=Map[Attributes,p],b,c,m,n},
ToExpression[{“ClearAttributes[”<>StrStr[p[[1]]]<>“,”<>ToString[a[[1]]]<>
“]”,“ClearAttributes[”<>StrStr[p[[2]]]<>“,”<>ToString[a[[2]]]<>“]”}];{b,c}=
ToExpression[{“ToString[Definition[”<>StrStr[p[[1]]]<>“]]”,
“ToString[Definition[”<>StrStr[p[[2]]]<>“]]”}];If[MemberQ[{b,c},“Null”],
Print[VarExch::“Bothargumentsshouldbedefinedbutuncertaintyhadbeen
detected:“,p];Return[],Null];{m,n}=Map4[StringPosition,Map[StrStr,{b,c}],
{”:=“,”=“}];
{n,m}={StringTake[b,{1,m[[1]][[1]]–1}]<>StringTake[c,{n[[1]][[1]],–1}],
StringTake[c,{1,n[[1]][[1]]–1}]<>StringTake[b,{m[[1]][[1]],–1}]};
ToExpression[{n,m}];Map[ToExpression,{“SetAttributes[”<>StrStr[p[[1]]]<>“,”
<>
ToString[a[[2]]]<>“]”,“SetAttributes[”<>StrStr[p[[2]]]<>“,”<>ToString[a[[1]]]
<>“]”}]];If[!ListListQ[L],Kr[L],For[k,k<=Length[L],k++,Kr[L[[k]]]]];]
In[2546]:=Agn=67;Avz:=72;Art:=25;Kr=18;SetAttributes[“Agn”,
Protected];SetAttributes[“Art”,{Protected,Listable}]In[2547]:=Map[Attributes,
{“Agn”,“Avz”,“x”,“y”,“Art”,“Kr”}]Out[2547]={{Protected},{},{},{},{Listable,
Protected},{}}
In[2548]:=VarExch[{{“Avz”,“Agn”},{“x”,“y”},{“Art”,“Kr”}}]
VarExch::Bothargumentsshouldbedefinedbutuncertaintyhadbeendetected:{x,y}
In[2549]:={Avz,Agn,Art,Kr}
Out[2549]={67,72,18,25}
In[2550]:=Map[Attributes,{“Agn”,“Avz”,“Art”,“Kr”}]
Out[2550]={{},{Protected},{},{Listable,Protected}}
In[2551]:=Rename[x_String/;HowAct[x],y_/;!HowAct[y]]:=Module[{a,c,d,b=
Flatten[{PureDefinition[x]}]},
If[!SameQ[b,{$Failed}],a=Attributes[x];c=ClearAllAttributes[x];d=
StringLength[x];c=Map[ToString[y]<>StringTake[#,{d+1,–1}]&,b];
Map[ToExpression,c];Clear[x];SetAttributes[y,a]]]In[2552]:=fm=“Art_Kr”;
SetAttributes[fm,{Protected,Listable}];