append(H|T],L)->H|append(T,L)] append(],L)->L. member(H,H|_])->true member(H,_|T])->member(H,T) member(_,])->false.
TheErlangprimitivedatatypesare:
atoms
-
true,foo,bar'HelloJoe'
Integers
-
1231461426412645317156,42
Floats
-
3.1415926535
Pids
-processidentiers
Refs
-guaranteeduniqueidentiers
Funs
-functionalobjects Complexdataobjectsarerepresentedas:
tuples
-forstoringaxednumberofobjects,thus:
{a,1234}
lists
-forstoringavariablenumberofobjects,thus:
a,23,hi]
Functionalobjectsareintroducedwiththesyntax:
fun(Arg1,..,ArgN)->...end.
So,forexample,thefollowingsequenceofexpres- sions:
K=2, F=fun(X)->X*Kend,
createsafunctionalobject
X*K
whichisboundto thevariable
F
.Inthisexpression
X
isafreevariable and
K
isboundtotheinteger2.Wecanevaluate
F
withthesyntax
F(Args)
.Functions(funs)arerstclassobjects-theycan bepassedasargumentstootherfunctionsorcanbe returnedbyfunctions.Toillustratethissupposewedenethehigherorder function
adder(C)
asfollows:
adder(C)->fun(X)->X+Cend.
Evaluating,forexample,
adder(10)
returnsafunc- tionwhichadds10toitsargument:
>Add10=adder(10). #Fun >Add10(5). 15
Suppose,also,thatwehavethefunction
map
de- nedasfollows:
map(F,H|T])->F(H)|map(T)] map(F,])->]
Wecanusethisasfollows:
>map(Add10,1,2,3,4,5]). 11,12,13,14,15]
Hereweusedthe
Add10
functionasanargumentto
map
.Listcomprehensionsareintroducedbythesyntax
Term||P1,P2,..,Pn]
whereeachofthe
Pi
'siseither ageneratoroftheform
Pattern<-Expression
ora predicate.Usinglistcomprehensionswecanwritethefamiliar quick-sortroutineasfollows:
sort(X|Xs])-> sort(Y||Y<-Xs,Y<X])++ X]++ sort(Y||Y<-Xs,Y>=X]) sort(])->].
Where
++
istheinxappendoperator.
3ConcurrentErlangPrograms
Erlangisa
concurrent
programminglanguage{ parallelactivitiescanbeprogrammedinErlangitself anddonotmakeuseofanyconcurrencymechanisms inthehostoperatingsystem.Erlanghasaprocessmodelofconcurrency.New processarecreatedbyevaluatingtheErlangprimitive
spawn
send(writtenwiththeinxoperator
!
)sends amessagetoaprocessand
receive
canbeusedto receiveamessage.Theprimitive
spawn(M,F,A1,A2,..,An])
cre- atesanewparallelprocess.Thisprocessevaluatesthe function
M:F(A1,A2,..,An)
.Whenthefunctioneval- uationhascompletedtheprocessdies.Wecanwritean
echo
processthus:
-module(echo). -export(start/0,loop/0]). start()-> spawn(echo,loop,]). loop()-> receive {From,Message}-> From!Message, loop() end. spawn(echo,loop,])
causesthefunctionrep- resentedby
echo:loop()
tobeevaluated
inparallel
withthecallingfunction.Thusevaluating:
Leave a Comment