2

I want to do the following in ghci, but apparently it does not allow me to do so:

charName :: Char -> String  
charName 'a' = "Albert"  
charName 'b' = "Broseph"  
charName 'c' = "Cecil" 

I could have done:

let charName 'a' = "Albert"  
let charName 'b' = "Broseph"  
let charName 'c' = "Cecil" 

But still, because of no charName :: Char -> String, it would fail the following:

charName 'a' 
"*** Exception: <interactive>:38:5-26: Non-exhaustive patterns in function charName

How can I solve this issue?

Qiang Li
  • 10,593
  • 21
  • 77
  • 148
  • 1
    The reason your `charName 'a'` doesn’t work here is not because of a missing type signature. Instead, your three definitions of `charName` overwrite each other; at the end, `charName` is only defined for `'c'`, because that came last. – chirlu Jul 23 '13 at 05:58
  • @chirlu: how can I define a type signature in `ghci`? – Qiang Li Jul 23 '13 at 06:33
  • @QiangLi use a semicolon between it and the function, or better, use the :{ approach as in the linked duplicate, but it's actually far easier to just pop yoiur definitions in a file and load them, because they're easier to read and edit there. – AndrewC Jul 23 '13 at 08:17

1 Answers1

0

You can use Braces and Semicolons instead of the white space rules:

Prelude> let {charName 'a' = "Albert"; charName 'b' = "Broseph"; charName 'c' = "Cecil"}
Prelude> charName 'a'
"Albert"
Prelude> charName 'b'
"Broseph"
firefrorefiddle
  • 3,795
  • 20
  • 31