Haskell-在列表中找到最小的元素 [英] Haskell - finding smallest Element in list

查看:93
本文介绍了Haskell-在列表中找到最小的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个获取列表并返回最小元素的函数.

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

我做错了什么?

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

推荐答案

如果您想以最Haskell的方式解决它.我会这样解决的:

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

但是我会使其更安全些,因为如果它为空,则列表中最小的int实际上为0吗?我认为您应该使用Nothing作为结果.

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

这篇关于Haskell-在列表中找到最小的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆