编写两个函数,在 Haskell 中返回列表的第一个和最后一个元素

sk-*_*sk- 0 haskell functional-programming

我对 Haskell 还很陌生,所以我仍然掌握着一切。我想编写两个函数,其中第一个函数接受一个整数列表并返回第一个元素。第二个函数执行相同的操作,但返回最后一个元素。到目前为止我有

firstList :: [Integer] -> Integer
firstList [] = 0
firstList (_:xs) = head xs

lastList :: [Integer] -> Integer
lastList [] = 0
lastList (_:xs) = (last) xs
Run Code Online (Sandbox Code Playgroud)

lastList 函数似乎在工作,但在 firstList 中不起作用。例如,对于列表 [3, 1, 2, 4]; 它返回 1 而不是 3。如何改进我的代码?

lef*_*out 5

您似乎混合了两种可能的方法来解决这个问题:

  1. 不费力的方法

    firstList :: [Integer] -> Integer
    firstList = head
    
    Run Code Online (Sandbox Code Playgroud)

    ...或通过 ?-expansion firstList xs = head xs。这只是调用标准head函数而不做任何其他事情。这当然是解决问题的一种方法,但可能不是此任务中的预期。

  2. 全手动方法

    firstList [] = ...
    firstList (x:xs) = ...
    
    Run Code Online (Sandbox Code Playgroud)

    在此设置中,您不会从库中调用任何内容,而是手动确定如何处理列表的头部和尾部(如果有)。嗯,因为firstList这很简单:您只需使用head 元素,即x. 无需再执行任何操作,无需调用其他函数。
    OTOH,因为lastList您实际上需要做更多事情。具体来说,正如 chi 所评论的那样,您实际上并没有处理 1 元素的情况,因为如果有的话,您总是会去掉头元素。如果那是唯一的元素,那么last就没有任何可用的元素。您实际上应该做的根本不是调用标准函数,而是手动处理所有相关情况并递归 用你自己的功能。

    lastList [] = ...
    lastList [x] = ...
    lastList (_:xs) = lastList xs
    
    Run Code Online (Sandbox Code Playgroud)