ブール条件が 4 つあり、そのうちの少なくとも 3 つが true である場合は_ _ を実行します。これを Haskell で実装することは可能ですか?
または、順列ごとに実行する必要がありますか? (つまり、1.True、2.True、3.True、4.False および 1.False、2.True、3.True、4.True など)
ありがとう!
ブール条件が 4 つあり、そのうちの少なくとも 3 つが true である場合は_ _ を実行します。これを Haskell で実装することは可能ですか?
または、順列ごとに実行する必要がありますか? (つまり、1.True、2.True、3.True、4.False および 1.False、2.True、3.True、4.True など)
ありがとう!
atleast :: Int -> [Bool] -> Bool
atleast n bools = length tn == n
where tn = take n . filter id $ bools
何かを見逃していない限り、怠惰に動作するはずです。
N 個の数が見つかったときにリストの調査を停止したい場合は、怠惰な自然数で数えることができます。
import Data.List
import Data.Number.Natural
atLeast :: Int -> [Bool] -> Bool
atLeast n = (>= (fromIntegral n :: Natural)) . genericLength . filter id
このソリューションは、これまでに提供された他のソリューションとは異なり、短絡する (つまり、 が見つかった後に停止するn
Bool
) という点で異なります。そのため、いくつかの無限リスト (最終的に に評価されるリストのみTrue
) を操作でき、必ずしもリスト内のすべての要素の評価を強制するわけではありません (怠惰のため)。
atLeast :: Int -> [Bool] -> Bool
atLeast 0 _ = True
atLeast _ [] = False
atLeast n (True:bs) = atLeast (n - 1) bs
atLeast n (False:bs) = atLeast n bs
各順列?もちろんそうではありません..真である条件の数を数えることができます。
それは最も美しい方法ではありませんが、あなたは見つけるかもしれません
atLeast :: Int -> [Bool] -> Bool
atLeast n bools = length (filter (==True) bools) >= n
最も理解しやすい。filter
指定したルールを満たすものだけをリストから保持します。この場合、ルールは答えが でなければならないということTrue
です。次に、length
残っている数を数えます。
(ルールは、リスト内の要素のタイプである関数です) a -> Bool
。a
atLeast3 :: Bool -> Bool -> Bool -> Bool -> Bool
atLeast3 b1 b2 b3 b4 = sum (map fromEnum [b1, b2, b3, b4]) >= 3
requireAtLeast :: Int -> [Bool] -> Bool
requireAtLeast n = (>= n) . length . filter id
極端に有意義または無意味なフォームを好む場合は、それぞれ次のとおりです。
requireAtLeast threshold predicates = length (filter (\predicate -> predicate) predicates) >= threshold
requireAtLeast = (. length . filter id) . (<=)