haskellrecursionfunctional-programmingpattern-matchingparse-error

Haskell - finding smallest Element in list


I have a function that gets a List and has to return the smallest Element of it.

Unfortunately I keep getting the issue:

Parse error in pattern: minim

What could I have done wrong?

minim :: [Int] -> Int
minim []       = 0
minim [x]      = x
minim x:xs     = min x (minim xs)

min :: Int -> Int -> Int
min a b
    | a > b  = b
    | a < b  = a

Solution

  • If you want to solve it the most Haskell way. I would solve it as such:

    -- Does not work for empty lists (so maybe needs to be wrapped in some logic)
    foldr1 min [-3,1,2,3]
    -- Works for empty but needs a "default value" (in this case 0)
    foldr min 0 [-3,1,2,3]
    

    If you want to learn by implementing it yourself, then this works for me

    minim :: [Int] -> Int
    minim []       = 0
    minim [x]      = x
    minim (x:xs)   = min x (minim xs)
    
    min :: Int -> Int -> Int
    min a b
        | a > b  = b
        | a < b  = a
        | a == b = a
    

    I would however make it a bit more safe, because is really 0 the smallest int in the list if it is empty? I think you should use Nothing as the result.

    import Data.Maybe
    
    import Prelude hiding (min)
    
    main = print $  minim [1,3,4, 6,6,-9]
    
    minim :: [Int] -> Maybe Int
    minim []       = Nothing
    minim [x]      = Just x
    minim (x:xs)   = min x <$> minim xs
    
    min :: Int -> Int -> Int
    min a b
        | a > b  = b
        | a < b  = a
        | a == b = a