次の関数が与えられた場合
maxInt :: Array Number -> Int
maxInt xs = fromMaybe 0 $ join $ fromNumber <$> maximum xs
maxInt [ 2.0, 4.0, 1.0, 5.0 ] => 5
これを行うためのよりエレガントな方法はありますか?剥ぎ取りがMaybe
多い
次の関数が与えられた場合
maxInt :: Array Number -> Int
maxInt xs = fromMaybe 0 $ join $ fromNumber <$> maximum xs
maxInt [ 2.0, 4.0, 1.0, 5.0 ] => 5
これを行うためのよりエレガントな方法はありますか?剥ぎ取りがMaybe
多い
最初に入力全体に適用してから、そのリストfromNumber
の最大値を取ります。このようにして、無効な値はすべて最初に変換され、無視されます。Nothing
maximum
maxInt = fromMaybe 0 . maximum . (map fromNumber)
(これは;Ord a => Maybe a
のインスタンスであるため機能し、値はどの値よりも小さく、値は基になる値によって順序付けられます。)Ord
Nothing
Just
Just
これにより、潜在的なバグも修正されfromNumber (maximum xs) == Nothing
ます。その場合、ではなくmaxInt
、わずかに小さい値があったとしても、 は 0 を返しy
ます。fromNumber y
Nothing
デフォルトのケース 0 でそれを処理してもよろしいですか? もしそうなら、あなたは探していますmaxInt xs = fromMaybe 0 $ fromNumber =<< maximum xs
。そうでない場合は、Maybe をそのままにして、 のようにしmaxInt = fromNumber <=< maximum
ます。