【问题标题】:Recursive Datatypes and types in Objective CObjective C 中的递归数据类型和类型
【发布时间】:2023-09-13 03:23:01
【问题描述】:

相关:
Lazy datatypes in Objective C

从相关问题中,我能够弄清楚如何使用块对象来模拟暂停计算,但我仍在努力掌握这个概念。对于horribleComputation,它可以工作,但是如何为无限流建模?

在 SML 中通常是如何完成的,

(* Have a datatype to wrap a computation *)
datatype 'a susp = Susp of (unit -> 'a)

(* Create a recursive datatype to handle an infinite stream  *)
datatype 'a stream = Cons of 'a * ('a stream') susp
type 'a stream = ('a stream') susp

现在在 Objective-C 中有 typedef,它接受预定义的值

enum suit {hearts, spades, diamonds, clubs};

我只是不知道如何获得Cons of 部分

目前,如果无法进行无限数据建模,如何建模例如一手牌。再次在 SML 中,

datatype suit = Clubs | Spades | Hearts | Diamonds
datatype rank = Two | Four | Five (*... etc *)

(* Then a card *)
type card = rank*suit

(* And now we can have a Hand :) *)
datatype hand = Empty | Hand of card * hand;

很可能所有内容都不可迁移,但我只是好奇我可以将 Objective C 用于惰性编程的效果如何……例如按需处理所有自然数。我一直在搜索这个。

【问题讨论】:

    标签: objective-c sml


    【解决方案1】:

    有两个独立的正交概念:递归数据类型和惰性计算。在 C 和类 C 语言中,您可以使用 struct 对前者建模,该 struct 包含指向自身的指针,或者指向包含/指向该 struct 的其他数据类型的指针。使用块对象或任何东西来暂停你的计算。将这两个概念结合在一起,得到一个struct,其中包含一个指向暂停计算的指针,该计算返回(指向)struct

    【讨论】: