1

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?

vik santata
  • 2,989
  • 8
  • 30
  • 52
  • `let sum [] = 0 ; sum (x:xs) = x + sum xs` (GHCi definition dialect). – Mephy Feb 05 '16 at 03:18
  • 3
    For this kind of issues, I recommend [Haskell for OCaml programmers](http://science.raphael.poss.name/haskell-for-ocaml-programmers.html#straightforward-equivalences) (even if I don't completely agree on all its suggestions). – chi Feb 05 '16 at 09:04

3 Answers3

7

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
dfeuer
  • 48,079
  • 5
  • 63
  • 167
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
  • I tried first one on ghc, got syntax error:let sum = \case []->0 x:xs->x+sum xs sum [1..10]. It says parse error on input `case' – vik santata Feb 05 '16 at 09:23
  • @vik: You need to allow for the extension `LambdaCase` in ghci. Before typing `let sum = ...`, you should type in ghci `:set -XLambdaCase`. See [here](http://stackoverflow.com/questions/12584884/how-do-i-enable-language-extensions-from-within-ghci). – isanco Feb 05 '16 at 15:27
  • Thanks, it works in ghci. But if I wish to use GHC to compile my code, how do I import? I tried "import LambdaCase", still says "parse error on input `case'. Am I using wrong import? – vik santata Feb 06 '16 at 01:30
  • @viksantata The first code block in my answer is a complete file you can compile. – Daniel Wagner Feb 06 '16 at 02:39
3
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
Alec
  • 31,829
  • 7
  • 67
  • 114
Zacharie 007
  • 126
  • 4
1

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'
Zacharie 007
  • 126
  • 4