考虑下面的代码示例,它创建了一个新类型来表示客户模型:
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,但是会产生一个错误:
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创建的对象的值?
发布于 2022-05-30 11:04:38
你必须做
first :: Customer -> String
first (Customer a) = _.firstname a因为newtype确实是一种新的类型。
发布于 2022-06-11 16:07:18
另一种方法是派生特定newtype的newtype实例,该实例公开某些函数,使您可以处理由Newtype包装的数据。
derive instance newtypeCustomer :: Newtype Customer _
first :: Customer -> String
first = (_.firstname <<< unwrap)https://stackoverflow.com/questions/72433059
复制相似问题