定义 Haskell 函数的默认返回值

问题描述 投票:0回答:1

我正在学习 Haskell,并且正在做 H99(99 个 Haskell 问题)。我正在研究第一组问题,主题是列表。我正在进行的练习要求返回列表的最后一个元素。我用三种不同的方式做到了:

-- first approach using conditions
myLast :: [Integer] -> Integer
myLast l =
    if null l then
        -1
    else
        l !! ((length l) - 1)
-- second approach using guards
myLast :: [Integer] -> Integer
myLast l
    | null l = -1
    | otherwise = l !! ((length l) - 1)
-- third approach using last function
myLast :: [Integer] -> Integer
myLast l
    | null l = -1
    | otherwise = last l

然后我想“尽管列表只接受唯一类型的元素,但我可以用两种可能的类型声明列表吗?”。显然我可以:

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...)。

提前致谢!

haskell functional-programming
1个回答
0
投票

标准库为您提供了

Maybe a

getLast :: [a] -> Maybe a

如果列表为空,您应该返回

Nothing
;如果
Just 11
是最后一个值,则返回
11
。我把它留作练习。

© www.soinside.com 2019 - 2024. All rights reserved.