You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell函数默认返回值定义:空列表场景处理疑问

学习Haskell的H99习题笔记与问题解答

我正在学习Haskell,正在完成H99(99道Haskell习题),当前在做列表相关的第一组习题,其中一道要求实现返回列表最后一个元素的功能,我用三种方式实现:

第一种:条件判断实现

-- first approach using conditions
myLast :: [Integer] -> Integer
myLast l =
    if null l then
        -1
    else
        l !! ((length l) - 1)

第二种:守卫(Guards)实现

-- second approach using guards
myLast :: [Integer] -> Integer
myLast l
    | null l = -1
    | otherwise = l !! ((length l) - 1)

第三种:调用内置last函数实现

-- third approach using last function
myLast :: [Integer] -> Integer
myLast l
    | null l = -1
    | otherwise = last l

扩展思考:支持多类型元素的列表

随后我思考:「尽管列表只能容纳同类型元素,能否声明可包含两种类型的列表?」显然可以,用Either类型就能实现:

myLast :: [Either Integer String] -> Either Integer String

但此时检查列表是否为空时遇到了问题:该返回什么?

myLast :: [Either Integer String] -> Either Integer String
myLast l =
    if null l then
        -- what should I return?
    else
        l !! ((length l) - 1)

因此我的问题是:能否为此函数定义空列表场景下的默认返回值?

我仅接触Haskell几天,之前熟悉Python、JavaScript、Java、C、Go等语言,可能遗漏了文档内容,提前感谢解答!


编辑:最终解决方案

首先感谢各位解答!不仅解决了问题,还帮我理解了一些概念。大家提供了一些术语供我搜索,我从昨天开始学习,再次感谢!

阅读评论并学习更多列表知识后,我得出如下解决方案:

myLast :: [a] -> Maybe a
myLast xs = case xs of
    [] -> Nothing
    [x] -> Just x
    (_:xs) -> myLast xs

经过几小时的学习,我开始理解相关概念,感到很开心,小进步也是进步,对吧?


内容的提问来源于stack exchange,提问作者Márcio Scotuzzi Jr.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:35:11