首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Idris自动售货机

Idris自动售货机
EN

Code Review用户
提问于 2015-12-01 03:38:12
回答 1查看 282关注 0票数 13

伊德里斯(基于Idris的类型驱动开发)演示了如何使用Idris为自动售货机构建有限状态机。

请批评我的执行情况。我是新的依赖类型,所以我不确定依赖类型是否会增强这种实现。换句话说,如果路径依赖类型会显著改善FSM,那么我不确定如何改进。

代码语言:javascript
复制
module VendingMachine

-- Pounds is a form of currency/money
Pounds : Type
Pounds = Nat

-- the Machine dispenses/vends chocolate candy bars
Choc : Type
Choc = Nat

data Machine = Mach Pounds Choc

fill : Machine -> Nat -> Machine
fill (Mach ps bars) ns = Mach ps (bars + ns)

init : Machine
init = Mach 0 0

insertCoin : Machine -> Machine
insertCoin (Mach ps bars) = (Mach (ps + 1) bars)

vend : Machine -> Machine
vend (Mach Z bars)          = Mach Z bars
vend (Mach (S ps) (S bars)) = Mach ps bars

getChange : Machine -> Machine
getChange (Mach Z bars) = Mach Z bars
getChange (Mach n bars) = Mach 0 bars
EN

回答 1

Code Review用户

发布于 2015-12-22 01:16:35

我试着搜索和搜索关于如何解决这类问题的变体,所有的搜索都会出现由您发布的帖子或对原始文档和效果库的引用。换句话说,Idris语言没有多少在线文档可供使用,我有点不确定是否值得使用这种语言。不过,我可以对代码和状态机中的一般问题发表一点意见:

  • 命名稍微不一致- For类型--我将使用PoundsChocolateBars (或Bars),并在使用参数时使用相应的poundsbars
  • 使用(S pounds)(pounds + 1)都要保持一致--试着坚持一个特定的表示法来表示递增的版本。Z0的使用也是如此。保持一致。
  • 一条巧克力的价格是多少?如果代码与vend相关的“S”"1磅“,那么使用getChange变体是没有意义的。这更像是一种removePounds方法。
  • 国家并不是相互关联的,- I将定义更多的州,而行动显然是与各州相关联的。就目前情况而言,insertCoinvend和可能的getChange操作之间没有联系。所有这些都可以按任意顺序执行,这取决于自动售货机中磅和棒的可用性。伪代码中的替代版本:
    • Empty - An空自动售货机,没有钱也没有酒吧
      • 操作:fill→状态:Idle:增加bars的数量

代码语言:javascript
复制
- `Idle` - A vending machine with no currently inserted money, but has bars  
    - action: `insertCoin` → state: `ReadyForVending`: changes the `coinInSlot` variable
    - action: `removePounds` → state: `Idle`: Clears the `pounds` variable
代码语言:javascript
复制
- `ReadyForVending` – With inserted money, and bars  
    - action: `vend` → state: `Idle`: Removes one `bars`, and clears `coinInSlot`
    - action: `returnCoin` →  state: `Idle`: Clear the `coinInSlot`

要实现这一点,除了coinInSlotpounds之外,您还需要另一个状态变量,如bars

  • Machine vs Mach还不清楚--我不确定你是否对这些内容有很好的理解,至少名字有点让人困惑。我认为,与其使用奇怪的Mach额外表示法,不如使用元组记录来描述内部状态,这也简化了下面的一些代码。
  • 对状态机使用效果--我找到的状态机(- In 联机编译器 )--不支持效果,但是我发现的文档(和一些幻灯片/帖子/论文)表明,要正确实现状态机,您应该使用效果库(刽子手),这在在线编译器中是不支持的。

我试着用http://www.tryidris.org的在线编译器编译一个新版本,但是错误很多,看起来有点不稳定。此外,当试图从OP获得有关您实际如何运行代码和预期输出的信息时,我没有得到多少响应。因此,我无法让您更好地实现Idris中的类型依赖状态机。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/112408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档