0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

もっと気持ち悪く if を関数化したい

Last updated at Posted at 2020-04-30

元ネタ:4歳娘「パパ、constしか使わないで?」

仕組みについては Haskell の記事を読んでいただきたく。

.js
// 代数的データ型を関数に、
// パターンマッチを関数適用に見立てる宣言
const caseOf = match => adt => adt(match);

// Haskell の Maybe を意識した何か
const Nothing = () => ({Nothing}) => Nothing();

const Just = x => ({Just}) => Just(x);

const guard = flg => flg ? Just() : Nothing();

const fmap = f => caseOf({
  Nothing,
  Just: x => Just(f(x))
});

const fromMaybe = v => caseOf({
  Nothing: () => v,
  Just: x => x
});

// 定数関数
const con$t = x => _ => x;

// ifの代替関数の作成用
const if_ = guard;

const then_ = x => fmap(con$t(x));

const else_ = fromMaybe;

const compose = fs => fs.reduce((g, f) => x => f(g(x)), x => x);

// 使用例
const dayText = compose([
  if_,
  then_(() => "お休み"),
  else_(() => "平日"),
  lazy => lazy()
]);

console.log(dayText(true));
//=> お休み

console.log(dayText(false));
//=> 平日
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?