如何柯里化布尔类型的内置函数(并将其设置为 1 或 0)?

发布于 2024-12-10 19:29:50 字数 450 浏览 4 评论 0原文

我认为我可以在给定函数调用的情况下将布尔本机类型设置为 true 或 false,但似乎没有按照我的预期

用特征更新

    has 'Lock'    => ( 
        is => 'ro', 
        isa => 'Bool', 
        traits => ['Bool'],
        default => 0 ,
        reader  => 'isLocked', 
        handles => {
            lock     => [ set => 1 ],
            unlock => [ set => 0 ],
            flip     => 'toggle',

        }
  ); 

I thought I could curry a Boolean native type to set to true or false given a function call, but doesn't seem to work how I expected

updated with traits

    has 'Lock'    => ( 
        is => 'ro', 
        isa => 'Bool', 
        traits => ['Bool'],
        default => 0 ,
        reader  => 'isLocked', 
        handles => {
            lock     => [ set => 1 ],
            unlock => [ set => 0 ],
            flip     => 'toggle',

        }
  ); 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧时模样 2024-12-17 19:29:50

我认为您正在寻找 Moose::Meta::Attribute::Native::Trait::Bool 此处,由 traits => 指定['布尔']

当你拥有的只是 isa =>; '布尔',默认 => 0,您的属性不包含对象。您无法调用数字 0 上的方法,因此如果没有本机特征的帮助,它就无法处理任何事情。

来自 Moose::Meta::Attribute::Native :“本机委托允许您将本机 Perl 数据结构委托给对象,就好像它们是对象一样。”这意味着当您将句柄与它们一起使用时,它们会生成特殊方法,这些方法对属性执行某些操作,而不是对存储在属性中的对象调用方法。 Bool 原生特征提供了 setunsettoggle 方法,这意味着您可以使用以下方法执行您想要的操作:

has 'Lock'    => ( 
    is => 'ro', 
    isa => 'Bool',
    traits => ['Bool'],
    default => 0 ,
    reader  => 'isLocked', 
    handles => {
        lock     => 'set',
        unlock   => 'unset',
        flip     => 'toggle',
    }
 );

I think you're looking for Moose::Meta::Attribute::Native::Trait::Bool here, specified by traits => ['Bool'].

When all you have is isa => 'Bool', default => 0, your attribute doesn't hold an object. You can't call methods on the number 0, so it can't handles anything without help from a native trait.

From Moose::Meta::Attribute::Native: "Native delegations allow you to delegate to native Perl data structures as if they were objects." That means that when you use handles with them, they generate special methods that perform certain operations on the attribute other than calling a method on an object stored within the attribute. The Bool native trait provides set, unset, and toggle methods, which means you can do what you want with:

has 'Lock'    => ( 
    is => 'ro', 
    isa => 'Bool',
    traits => ['Bool'],
    default => 0 ,
    reader  => 'isLocked', 
    handles => {
        lock     => 'set',
        unlock   => 'unset',
        flip     => 'toggle',
    }
 );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文