1

よりエレガントに表現できると思われるパターンに出会いました。

私は2つの関数f1,f2 :: Int -> Int(それらの実装は関係ありません)と、次のことを行う aprocess :: Int -> Intを持っています:

  • と異なる場合f1 xは、プロセスを繰り返しますx1xx1
  • それ以外の場合、と異なる場合f2 xは、プロセスを繰り返しますx2xx2
  • 最後に、プロセスを停止して戻りますx

私のcase ... of実装は次のとおりです。

f1 :: Int -> Int
f1 = undefined

f2 :: Int -> Int
f2 = undefined

process :: Int -> Int
process x =
    case f1 x of
        x ->
            case f2 x of
                x -> x
                x' -> process x'
        x' -> process x'

次の警告が生成されます。

so.hs:13:17: warning: [-Woverlapping-patterns]
    Pattern match is redundant
    In a case alternative: x' -> ...
   |
13 |                 x' -> process x'
   |                 ^^^^^^^^^^^^^^^^

so.hs:14:9: warning: [-Woverlapping-patterns]
    Pattern match is redundant
    In a case alternative: x' -> ...
   |
14 |         x' -> process x'
   |         ^^^^^^^^^^^^^^^^

processどのパターンが重複しているか、よりエレガントに実装する方法について、誰かが光を当てることができますか?

4

2 に答える 2

5

Benのアドバイスに従って、私は次のように書きました。

process :: Int -> Int
process x
    | x /= x1 = process x1
    | x /= x2 = process x2
    | otherwise = x
  where
    x1 = f1 x
    x2 = f2 x
于 2021-12-19T22:24:35.987 に答える