如何在 Haskell 中编写具有初始条件的递归函数?

How to write a recursive function with initial condition in Haskell?

在 F# 中我可以这样定义:

let rec sum = function
| [] -> 0
| x::xs -> x + sum xs

看起来很方便。 Haskell中有它的对应吗?

假设您喜欢的功能是 "I don't have to repeat the name sum",LambdaCase 扩展可以启用此功能:

{-# LANGUAGE LambdaCase #-}

module CaseExample where
import Prelude hiding (sum)

sum = \case
    [] -> 0
    x:xs -> x + sum xs

否则,没有扩展名的语法是

sum [] = 0
sum (x:xs) = x + sum xs
sum :: [Int] -> Int

sum [] = 0
sum (x:xs) = x + sum xs

另一种方式

 Prelude>:{
 Prelude|let sumE  xs' = case xs' of
 Prelude|                     [] -> 0
 Prelude|                     x:xs' -> x + sumE xs'
 Prelude| 
 Prelude|:}
 Prelude> sumE [1,2,3]
 6
 Prelude> sumE []
 0

这将允许您编写多行代码:

  Prelude> :set +m

然后试试这个代码。提示符从 prelude> 变为 prelude| :

Prelude> let sumE  xs' = case xs' of
Prelude|                     [] -> 0
Prelude|                     x:xs' -> x + sumE xs'