在FIFO的数据结构中,第一个加入队列的元素也将是第一个被移除的元素。也就是说,一旦添加了新元素,必须先移除之前添加的所有元素,才能移除新元素。
来源:Investopedia
在智能合约中,实现FIFO队列可以用于许多场景,例如公平的排队系统,每个人都按照他们到达的顺序得到服务(或处理)。
我们直接开始编写一个FIFO合约。合约的两个主要运算将是push
(用于向队列添加元素)和pop
(用于从队列中移除元素)。
合约将队列存储在其存储空间中的列表中,每次push
运算都会将一个元素追加到列表的末尾,而每次pop
运算都会从列表的开头移除一个元素。
合约代码如下:
Python
import smartpy as sp
@sp.module
def main():
# The Fifo class defines a simple contract that handles push and pop instructions
# on a first-in first-out basis.
class SimpleFifo(sp.Contract):
def __init__(self):
self.data.first = 0
self.data.last = -1
self.data.saved = {}
@sp.entrypoint
def pop(self):
assert self.data.first < self.data.last
del self.data.saved[self.data.first]
self.data.first += 1
@sp.entrypoint
def push(self, element):
self.data.last += 1
self.data.saved[self.data.last] = element
@sp.onchain_view
def head(self):
return self.data.saved[self.data.first]
if "templates" not in __name__:
@sp.add_test(name="Fifo")
def test():
scenario = sp.test_scenario(main)
scenario.h1("Simple Fifo Contract")
c1 = main.SimpleFifo()
scenario += c1
c1.push(4)
c1.push(5)
c1.push(6)
c1.push(7)
c1.pop()
scenario.verify(sp.View(c1, "head")() == 5)
测试FIFO合约:
第一步:复制合约代码并粘贴至SmartPy IDE中。
第二步:点击右上角的Run
按钮来编译和模拟合约。
第三步:查看IDE右侧的模拟结果。你将看到每次运算后合同存储的状态。
第四步:尝试更改运算的顺序或添加新运算。
现在,你已经学会了如何在Tezos区块链上创建FIFO合约!在下一课中,我们将进一步介绍SmartPy的一个强大功能——递归,可以让合约调用自身。祝大家编程愉快!
在FIFO的数据结构中,第一个加入队列的元素也将是第一个被移除的元素。也就是说,一旦添加了新元素,必须先移除之前添加的所有元素,才能移除新元素。
来源:Investopedia
在智能合约中,实现FIFO队列可以用于许多场景,例如公平的排队系统,每个人都按照他们到达的顺序得到服务(或处理)。
我们直接开始编写一个FIFO合约。合约的两个主要运算将是push
(用于向队列添加元素)和pop
(用于从队列中移除元素)。
合约将队列存储在其存储空间中的列表中,每次push
运算都会将一个元素追加到列表的末尾,而每次pop
运算都会从列表的开头移除一个元素。
合约代码如下:
Python
import smartpy as sp
@sp.module
def main():
# The Fifo class defines a simple contract that handles push and pop instructions
# on a first-in first-out basis.
class SimpleFifo(sp.Contract):
def __init__(self):
self.data.first = 0
self.data.last = -1
self.data.saved = {}
@sp.entrypoint
def pop(self):
assert self.data.first < self.data.last
del self.data.saved[self.data.first]
self.data.first += 1
@sp.entrypoint
def push(self, element):
self.data.last += 1
self.data.saved[self.data.last] = element
@sp.onchain_view
def head(self):
return self.data.saved[self.data.first]
if "templates" not in __name__:
@sp.add_test(name="Fifo")
def test():
scenario = sp.test_scenario(main)
scenario.h1("Simple Fifo Contract")
c1 = main.SimpleFifo()
scenario += c1
c1.push(4)
c1.push(5)
c1.push(6)
c1.push(7)
c1.pop()
scenario.verify(sp.View(c1, "head")() == 5)
测试FIFO合约:
第一步:复制合约代码并粘贴至SmartPy IDE中。
第二步:点击右上角的Run
按钮来编译和模拟合约。
第三步:查看IDE右侧的模拟结果。你将看到每次运算后合同存储的状态。
第四步:尝试更改运算的顺序或添加新运算。
现在,你已经学会了如何在Tezos区块链上创建FIFO合约!在下一课中,我们将进一步介绍SmartPy的一个强大功能——递归,可以让合约调用自身。祝大家编程愉快!