Search code examples
haskelltypespattern-matchingghci

GHCi: cannot pattern match over custom type


I have defined a custom type for vectors of type Int:

data Vector = Vector Int Int Int

Now I want to define a function to add a vector to another, but somehow the syntax is incorrect, even though its very similar to the one employed in Learn You a Haskell For Great Good!.

First try, with prefix notation:

    Prelude> let vp :: Vector -> Vector -> Vector
    Prelude| vp (Vector a b c) (Vector d e f) = Vector (a+d) (b+e) (c+f)

    <interactive>:33:1: parse error on input ‘vp’

Second try, with infix notation:

    Prelude> let vp :: Vector -> Vector -> Vector
    Prelude| (Vector a b c) `vp` (Vector d e f) = Vector (a+d) (b+e) (c+f)

    <interactive>:35:1: parse error on input ‘(’

I'm using GHCI v7.8.4


Solution

  • It is just an indentation error

    Prelude> data Vector = Vector Int Int Int deriving Show
    Prelude> :{
    Prelude| let vp :: Vector -> Vector -> Vector
    Prelude|     vp (Vector a b c) (Vector d e f) = Vector (a + d) (b + e) (c + f)
    Prelude| :}
    Prelude> vp (Vector 1 2 3) (Vector 4 8 12)
    Vector 5 10 15
    

    works just fine, and so does

    Prelude> :{
    Prelude| let vp :: Vector -> Vector -> Vector
    Prelude|     Vector a b c `vp` Vector d e f = Vector (a + d) (b + e) (c + f)
    Prelude| :}