如何在`data`中正确解包`data`?

时间:2016-03-05 14:01:10

标签: purescript

我正在尝试访问嵌套数据(Foo.y在下面的示例中的Bar),但是想到在Foo内展开Bar的直接方法是我想到的不工作。但是如何正确打开它?

这是我的数据:

module Foo where

import Prelude

data Foo = Foo { y :: Int }

data Bar = Bar { x   :: Int
               , foo :: Foo }

以下(当然)不编译,错误为Could not match type { y :: Int } with type Foo - 就像Bar一样,Foo需要首先解包:

fn1 :: Bar -> Int
fn1 (Bar { x, foo }) = x + foo.y

所以我对下面的内容寄予了希望,但是唉,编译器说“不”(Foo构造函数周围的括号没有帮助):

fn2 :: Bar -> Int
fn2 (Bar { x, Foo { y } }) = x + y

fn3 :: Bar -> Int
fn3 (Bar { x, Foo f }) = x + f.y

以下工作,使用辅助函数进行解包,但必须有更好的方法:

getY (Foo foo) = foo -- helper function

fn4 :: Bar -> Int
fn4 (Bar { x, foo }) = let foo2 = getY foo in
                       x + foo2.y

那么,如何嵌套“展开”?

[编辑]

经过一两个小时的尝试后,我想出了这个,这有效:

fn5 :: Bar -> Int
fn5 (Bar { x, foo = (Foo f) }) = x + f.y

这是惯用的方式吗?为什么fn2fn3无效?

1 个答案:

答案 0 :(得分:3)

函数 fn2 fn3 不起作用,因为编译器不知道您指的是哪个记录字段( foo )。您必须按名称引用记录字段。

函数 fn4 是一个非常好的解决方案(尽管你的命名非常混乱, getY 实际上会返回 Foo 构造函数中的包装记录,不是 y 值。)

据我所知, fn5 是最短的解决方案。我个人更喜欢辅助功能(如第四个例子):

getY :: Foo -> Int
getY (Foo rec) = rec.y

fn6 :: Bar -> Int
fn6 (Bar { x, foo }) = x + getY foo