简体   繁体   English

使用不可变对象的F#待办事项列表

[英]F# todo list using immutable objects

I'm trying to figure out how to do a to do list in F# using immutable objects. 我试图弄清楚如何使用不可变对象在F#中执行待办事项清单。 The to do list (not necessarily an F# list) might be pulled from a database or collected from user input or read from XML or JSON, etc. That part is not so important. 待办事项列表(不一定是F#列表)可以从数据库中提取,也可以从用户输入中收集,或者从XML或JSON中读取,等等。这部分并不那么重要。

Pseudo code: 伪代码:

do for some length of time:
   for each item in the to do list:
      if item is ready to do:
         do item
         if it worked:
            remove from the todo list

   wait a bit before trying again
report on items that weren't ready or that failed.   

The to do list will be some collection of F# records which will have at least an instruction ("Send Email", "Start a process", "Copy a File", "Ask for a raise") along with parameters as a sub-collection. 待办事项清单将是一些F#记录的集合,这些记录至少具有一条指令(“发送电子邮件”,“开始处理”,“复制文件”,“要求加薪”)以及参数作为子菜单,采集。

Can such a thing be done with immutable objects alone? 这样的事情能否仅通过不可变的对象完成? Or must I use a .NET List or some other mutable object? 还是必须使用.NET列表或其他可变对象?

I don't need fully-fleshed out working code, just some ideas about how I'd put such a thing together. 我不需要完整的工作代码,只需一些有关如何将这种东西组合在一起的想法。

UPDATE: First attempt at (half-)coding this thing: 更新:第一次尝试对这个东西进行(半)编码:

let processtodo list waittime deadline = 
    let rec inner list newlist =
        match list with
        | [] when not List.isEmpty newlist ->
                inner newlist []

        | head :: tail when head.isReady->
                let res = head.action
                inner tail ( if res = true then tail else list)

        | head :: tail when not head.isReady ->
                inner tail list

        | _ when deadline not passed ->
            // wait for the waittime
            inner list
        | _ -> report on unfinished list

    inner list []

I tried to write this in the typical fashion seen in many examples. 我试图以许多示例中所见的典型方式编写此代码。 I assumed that the items support the "isReady" and "action" methods. 我假设这些项目支持“ isReady”和“ action”方法。 The thing I don't like is its not tail-call recursive, so will consume stack space for each recursion. 我不喜欢的是它不是尾调用递归,因此每次递归都会占用堆栈空间。

Recursion and/or continuations are the typical strategies to transform code with mutable structures in loops to immutable structures. 递归和/或延续是将循环中具有可变结构的代码转换为不可变结构的典型策略。 If you know how to write a recursive "List.filter" then you'll probably have some ideas to be on the right track. 如果您知道如何编写递归“ List.filter”,那么您可能会想到一些正确的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM