Objective C 中的惰性数据类型 [英] Lazy datatypes in Objective C

查看:61
本文介绍了Objective C 中的惰性数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SML 中,可以使用以下方法对惰性编程进行建模,

In SML, the following is possible for modelling lazy programming,

// Have a datatype to wrap a computation
datatype 'a susp = Susp of (unit -> 'a)
// A function to hold the computation
fun delay(f ) = Susp(f)

我知道可以使用

int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};

所以我想我可以将它用作函数参数.下一步是如何使用没有实参的函数(unit value 例如在 SML fn () =>) 并像上面一样创建惰性数据类型.

So I think I can use it as a function argument. The next step would be how to use functions with no real arguments ( unit value e.g. in SML fn () =>) and creating lazy datatypes as the one above.

这是可能的还是我应该追求一种不同的更明显的方式?

最终目标是从 SML 模拟挂起的计算行为,

The end goal would be to emulate the suspended computation behaviour from SML,

let val x = Susp(fn () => horribleComp(345))
in 
   force(x) + force(x)
end

力(x)在哪里

fun force (Susp(f)) = f ()

推荐答案

很酷的问题!

可以在 Objective-C 中实现一个惰性容器,如下所示(但你可能不应该,见下文):

You could implement a lazy container in Objective-C as follows (but you probably shouldn't, see below):

typedef id (^SuspBlock)(void);

@interface Susp : NSObjecti
- (id)initWithBlock:(SuspBlock)block;
+ (id)withBlock:(SuspBlock)block;
- (id)force;
@end

// -----

@interface Susp ()
@property (nonatomic, copy) SuspBlock _block;
@end

@implementation Susp
@synthesize _block;

- (id)initWithBlock:(SuspBlock)block {
  self = [super init];
  if (self != nil) {
    self._block = block;
  }

  return self
}

+ (id)withBlock:(SuspBlock)block {
  return [[[self alloc] initWithBlock:bloc] autorelease];
}

- (id)force {
  return self._block();
}

- (void)dealloc {
 self._block = nil;
 [super dealloc];
}

@end

那是很多样板,但不管怎样.然后,您可以像这样使用它:

That's a lot of boilerplate, but whatever. Then, you could use it like this:

id x = [Susp withBlock:^{ return someComputation(); }];
id result = [[x force] plus:[x force]];
// assuming the result of your computation has -plus:

但这一切都相当愚蠢,因为对于您正在做的事情,您确实不需要其他数据类型.只需使用块作为你的数据类型:

But that's all rather silly, since for what you're doing, you really don't need another data type. Just use blocks as your datatype:

typedef id (^SuspVal)(void);
SuspVal x = ^{ return complicatedThing; };
id result = [x() plus:x()];

这是一种更紧凑、更惯用的处理方式,这就是我的建议.除非您需要为惰性对象添加超出块基本实用程序的进一步语义,否则您不应不必要地包装它们.

That's a much more compact, idiomatic way of going about it, and it's what I suggest. Unless you need to add further semantics to your lazy objects that go beyond the basic utilities of blocks, you shouldn't wrap them needlessly.

干杯!

这篇关于Objective C 中的惰性数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆