LoginSignup
9
2

More than 5 years have passed since last update.

関数定義におけるパターンマッチング - Haskell vs Elm vs Elixir

Last updated at Posted at 2018-04-09

 Elmでちょっと嵌りまして、関数の定義でパターンマッチングは使えなかったんですね。コンパイラに怒られて、少し呆然としました。
Cannot use pattern matching in function definition - elm-lang/elm-compiler

 Haskellだと以下のように書けます。きれいですね。

factorial
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)

 しかしElmだと以下のようになります。関数の定義で場合分けができないから、caseで分けます。ちょっとHaskellより見劣りします。

factorial
factorial : Int -> Int
factorial n =
  case n of
    0 ->
      1
    _ ->
      n * factorial (n - 1)

 Elixirで書くと以下のようになりますね。Haskellに似ています。と言うか、一般的にElixirはHaskell以上に関数定義でのパターンマッチングを推奨しているような気もしますが。

factorial
defmodule Fact do
  def factorial(0), do: 1
  def factorial(n) when n > 0 do
    n * factorial(n - 1)
  end
end

 以上です

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