In F# I can define like this:
let rec sum = function
| [] -> 0
| x::xs -> x + sum xs
Looks quite convenient. Is there its correspondence in Haskell?
In F# I can define like this:
let rec sum = function
| [] -> 0
| x::xs -> x + sum xs
Looks quite convenient. Is there its correspondence in Haskell?
Assuming the feature you like is "I don't have to repeat the name sum", the LambdaCase extension enables this:
{-# LANGUAGE LambdaCase #-}
module CaseExample where
import Prelude hiding (sum)
sum = \case
[] -> 0
x:xs -> x + sum xs
Otherwise, the syntax that works without extensions is
sum [] = 0
sum (x:xs) = x + sum xs
sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x + sum xs
Another way
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
This will alow you to write multiple lines of code:
Prelude> :set +m
Then try this code. The prompt changes from prelude> to prelude| :
Prelude> let sumE xs' = case xs' of
Prelude| [] -> 0
Prelude| x:xs' -> x + sumE xs'