How to avoid unnecessary calculations?

I need to return false if the test failed for more than 3 items in the list. Is there something I can do to optimize?

isItemOk :: Integer -> Boolean 
isItemOk = ( some costly opernation )

This is the feature I'm trying to optimize,

isListOk :: [Integer] -> Boolean 
isListOk = 3 >= sum ( [ 1 | x <- [1.1000], isItemOk x ])

My attempt at optimization, assuming that if he finds 4 elements, will no longer search.

isListOk :: [Integer] -> Boolean 
isListOk = 3 >= sum ( take 4 [ 1 | x <- [1.1000], isItemOk x ])

Thank.

+5
source share
4 answers

You can just use filterwith something that checks for errors, and then take 4see how many items you have with length.

, - , . , , , .

, , " , ", ", " - . take - , . " null ", . , !

+8

, 3, .

case filter isItemOk xs of
   x1 : x2 : x3 : _ -> ...
   _                -> ... 
+6

, . genericLength,

import Data.Number.Natural
import Data.List
isListOk = (3 :: Natural) >= genericLength (filter isItemOk [1..1000])

, : , . :

> (3 :: Natural) >= genericLength (filter even (2:4:6:8:undefined))
False
+5

,

isListOk :: Bool 
isListOk = length (filter isItemOk [1 .. 1000]) <= 3

, , . ( , , . , 1 .. 1000, 1.1000.)

- , , .

, length ( 1, , ) . length : , , , .

, (.. ) , , :

isNotLongerThan :: [a] -> Integer -> Bool
isNotLongerThan []       n = n >= 0
isNotLongerThan (_ : xs) n = n >= 1 && isNotLongerThan xs (n - 1)

isListOk :: Bool 
isListOk = filter isItemOk [1 .. 1000] `isNotLongerThan` 3

, , , :

forNoMoreThan :: (a -> Bool) -> Integer -> [a] -> Bool
forNoMoreThan p n = (`isNotLongerThan` n) . filter p

isListOk :: Bool
isListOk = (isItemOk `forNoMoreThan` 3) [1 .. 1000]

Finally, as the hammar points out, if your threshold is small enough and fixed, you can simply use pattern matching to determine if the list is enough.

+4
source

All Articles