エージェントに情報を保存する方法と,その情報への問合わせについて説明します.教科書p.50 "3.2 エージェントをプログラムする" の内容に相当します.
class ODB_aomori extends TAG { def onsenlist def setup() { onsenlist = [ [name:'湯野川温泉', type:'単純泉', city:'川内町', point:80], [name:'湯坂温泉', type:'単純硫化水素泉', city:'大畑町', point:50], [name:'大間温泉', type:'食塩泉', city:'大間町', point:30] ] } def loop(msg) { println msg if (msg._p=='request-information') { if (msg.name != null) { // 温泉名による検索 def onsen = onsenlist.find{it.name==msg.name} if (onsen!=null) { reply(msg, [_p:'inform', name:onsen.name, type:onsen.type, city:onsen.city, point:onsen.point]) } else { reply(msg, [_p:'retrieve-faild', name:msg.name, type:'unknown', city:'unknown', point:'unknown']) } return } else if (msg.type != null) { // 泉質による検索 def onsen = onsenlist.find{it.type==msg.type} if (onsen!=null) { reply(msg, [_p:'inform', name:onsen.name, type:onsen.type, city:onsen.city, point:onsen.point]) } else { reply(msg, [_p:'retrieve-faild', name:msg.name, type:'unknown', city:'unknown', point:'unknown']) } return } else if (msg.point == 'max') { // 評価値による検索 def onsen = onsenlist.max{it.point} reply(msg, [_p:'inform', name:onsen.name, type:onsen.type, city:onsen.city, point:onsen.point]) return } } reply(msg, [_p:'sorry', msg:msg]) } }
def onsenlist
で変数onsenlist
を宣言します.型の指定は不要です.setup()
はエージェント起動後に実行されます.変数onsenlist
に温泉データを格納します.loop()
を実行します. msg
は届いたメッセージです.onsenlist.find{...}
はonsenlist
からデータを検索する書き方です.
{...}
はクロージャというGroovyの文法要素です.it
はクロージャが受け取った値です.今回の例ではonsenlist
の3つの要素が順にit
の値となります.onsenlist.max{it.point}
は,pointの要素が最高である要素をonsenlistから見つける書き方です.[_p:'request-information', name:'湯野川温泉']
を送ると,次のデータが返ってきます:[_p:'inform', name:'湯野川温泉', type:'単純泉', city:'川内町', point:80, _f:'ODB_aomori']
[_p:'request-information', type:'食塩泉']
を送ると,次のデータが返ってきます:[_p:'inform', name:'大間温泉', type:'食塩泉', city:'大間町', point:30, _f:'ODB_aomori']
[_p:'request-information', point:'max']
を送ると,次のデータが返ってきます:[_p:'inform', name:'湯野川温泉', type:'単純泉', city:'川内町', point:80, _f:'ODB_aomori']
onsenlist
に登録されていない温泉名を検索すると何が返るか調べてみましょう.