14.11.2012 Views

Curry: An Integrated Functional Logic Language

Curry: An Integrated Functional Logic Language

Curry: An Integrated Functional Logic Language

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A.6 Concurrent Object-Oriented Programming<br />

The following example shows a simple method to program in a concurrent object-oriented style in<br />

<strong>Curry</strong>. For this purpose, an object is a process waiting for incoming messages. The local state is a<br />

parameter of this process. Thus, a process is a function of type<br />

State -> [Message] -> Success<br />

In the subsequent example, we implement a bank account as an object waiting for messages of the<br />

form Deposit i, Withdraw i, or Balance i. Thus, the bank account can be defined as follows:<br />

data Message = Deposit Int | Withdraw Int | Balance Int<br />

account :: Int -> [Message] -> Success<br />

account eval rigid -- account is a consumer<br />

account _ [] = success<br />

account n (Deposit a : ms) = account (n+a) ms<br />

account n (Withdraw a : ms) = account (n-a) ms<br />

account n (Balance b : ms) = b=:=n & account n ms<br />

-- Install an initial account with message stream s:<br />

make_account s = account 0 s<br />

A new account object is created by the constraint make_account s where s is a free variable.<br />

When s is instantiated with messages, the account process starts processing these messages. The<br />

following concurrent conjunction of constraints creates an account and sends messages:<br />

make_account s & s=:=[Deposit 200, Deposit 50, Balance b]<br />

After this goal is solved, the free variable b has been bound to 250 representing the balance after<br />

the two deposits.<br />

To show a client-server interaction, we define a client of a bank account who is finished if his<br />

account is 50, buys things for 30 if his account is greater than 50, and works for an income of<br />

70 if his account is less than 50. In order to get the client program independent of the account<br />

processing, the client sends messages to his account. Therefore, the client is implemented as follows:<br />

-- Send a message to an object identified by its message stream obj:<br />

sendMsg :: [msg] -> msg -> [msg]<br />

sendMsg msg obj | obj =:= msg:obj1 = obj1 where obj1 free<br />

-- Client process of an bank account<br />

client s | s1 =:= sendMsg (Balance b) s =<br />

if b==50 then s1=:=[] -- stop<br />

else if b>50 then client (sendMsg (Withdraw 30) s1) -- buy<br />

else client (sendMsg (Deposit 70) s1) -- work<br />

where s1,b free<br />

44

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!