LoginSignup
10
2

More than 3 years have passed since last update.

Elmで関数と関数は比較できない。が、全く同じ場合は同じになるようだ。

Last updated at Posted at 2019-05-12

まとめ

>  (==) (\x -> x) (\x -> x)
Error: Trying to use `(==)` on functions.
There is no way to know if functions are "the same" in the Elm sense.
Read more about this at https://package.elm-lang.org/packages/elm/core/latest/Basics#== which describes why it is this way and what the better version will look like.>
> funcHoge x = x
<function> : a -> a
> (==) funcHoge funcHoge
True : Bool
> funcFuga=funcHoge
<function> : a -> a
> (==) funcHoge funcFuga
True : Bool
> funcPiyo x = x
<function> : a -> a
> (==) funcHoge funcPiyo
Error: Trying to use `(==)` on functions.
There is no way to know if functions are "the same" in the Elm sense.
Read more about this at https://package.elm-lang.org/packages/elm/core/latest/Basics#== which describes why it is this way and what the better version will look like.>

本文

タイトル意味不明でごめんなさい。

Elmで関数同士を比較して遊んでたら、 @ababup1192 先生から「関数同士は比較できないのでは」との指摘を受けた。しかし、一部ケースでは比較できてしまっていた。

ソースコードを調べてみると、
https://github.com/elm/core/blob/1.0.2/src/Elm/Kernel/Utils.js#L35-L44
あたりで (==) の実装が行われていた。
これをみると、
1. javascriptで === で比較し、trueであれば、その時点でtrueが返る。
2. もし成立しなければ、関数は object でも null でもないので、if文の中に入り、 function であるので、
3. https://github.com/elm/core/blob/1.0.2/src/Elm/Kernel/Debug.js#L262-L263 が呼ばれる。

つまり、関数同士を比較すると、全く同じものであれば true が、そうでなければ error として返ってくる。
「全く同じもの」である定義としては、「別名をつける」は含まれるが、「同じ定義である別関数」は含まれないようだ。(それはそうか、比較しようがないし)

というわけであまり使い道がないが、関数同士は全く同じであれば比較できるようだ。

10
2
1

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
10
2