Haskell - finding smallest Element in list

爷,独闯天下 提交于 2019-12-12 03:35:20

问题


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

回答1:


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



回答2:


You have one parameter that you want to match (the list of Ints). Where you want to match parts of that list you need to put these in brackets to show the compiler you are matching one thing. Thus the last pattern should be (x:xs).




回答3:


here's another way of implementing what you asked but without having to use auxiliary functions such as min

minElem::[Int]->Int
minElem [] = 0
minElem [x] = x
minElem (x:y:xs) 
 |x > y = minElem (y:xs)
 |x < y = minElem (x:xs)
 |x == y = minElem (x:xs)


来源:https://stackoverflow.com/questions/42530122/haskell-finding-smallest-element-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!