0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSのように簡潔にレコードからデータを取り出す方法

Last updated at Posted at 2023-11-09

モチベーション

Javascriptでは destructuring assignment 記法で簡潔にデータが取り出せる。
Haskellにも似たような方法があるけど、もっと使い勝手をJSに近づけたい。

const obj = {
    foo: "FOO",
    bar: "BAR",
    baz: "BAZ",
    qux: "QUX",
};

↑のデータから barbaz だけを簡単に取り出したい場合は↓のようにできる。

const { bar, baz } = obj;

方法

NamedFieldPuns 言語拡張を使う。

data Options = Options
    { optionsFoo :: Natural
    , optionsSrcFilePath :: !Text
    , optionsDestFilePath :: !Text
    , optionsBar :: Maybe Int
    }

この言語拡張を有効にすると、↑のような型があったとすれば、例えば↓のような感じで特定のデータを取り出せる。

Options { optionsSrcFilePath, optionsDestFilePath } <- view optionsL

参考文献

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?