首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PureScript - NewType的访问属性

PureScript - NewType的访问属性
EN

Stack Overflow用户
提问于 2022-05-30 10:46:00
回答 2查看 73关注 0票数 3

考虑下面的代码示例,它创建了一个新类型来表示客户模型:

代码语言:javascript
复制
module Main where

import Effect (Effect)
import Effect.Console ( logShow )
import Prelude (Unit,(+),(/),(*),(-), (<>),discard)

newtype Customer 
  = Customer
  { firstname :: String
  }

sample :: Customer
sample = Customer
  { firstname : "Average"
  }

first :: Customer -> String
first a = _.firstname a

main = do
  logShow ( first sample )

预期的输出将是值Average,它等于sample.name,但是会产生一个错误:

代码语言:javascript
复制
 Could not match type
  
    { firstname :: t0
    | t1
    }
  
  with type
  
    Customer
  

while checking that type Customer
  is at least as general as type { firstname :: t0
                                 | t1
                                 }
while checking that expression a
  has type { firstname :: t0
           | t1
           }
in value declaration first

where t0 is an unknown type
      t1 is an unknown type

这是一个很好的错误,但并没有解释如何实际访问这个值。

如何访问作为newType创建的对象的值?

EN

回答 2

Stack Overflow用户

发布于 2022-05-30 11:04:38

你必须做

代码语言:javascript
复制
first :: Customer -> String
first (Customer a) = _.firstname a

因为newtype确实是一种新的类型。

票数 3
EN

Stack Overflow用户

发布于 2022-06-11 16:07:18

另一种方法是派生特定newtype的newtype实例,该实例公开某些函数,使您可以处理由Newtype包装的数据。

代码语言:javascript
复制
derive instance newtypeCustomer :: Newtype Customer _
 
first :: Customer -> String
first  = (_.firstname <<< unwrap)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72433059

复制
相关文章

相似问题

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