Heinrich
Heinrich

Reputation: 289

Haskell - types/pattern matching

the following code does not compile. I get a type error. I thought this would be the nicer version, as it clearly seperates the two different cases... The function is supposed to help decide whether a Finite State Machine accepts an input word.

import Text.Show.Functions
import qualified Data.Set as Set
import qualified Data.List as List

setTransition :: (Int -> Char -> [Int])  -> [Int] -> Char -> [Int]
setTransition delta [] sigma            = []
setTransition delta xs@[x:xs'] sigma    = foldl f [] xs
                where f ys q = (delta q sigma) `List.union` ys

This (removed the patternmatching) however does compile. Can somebody tell me why??

import Text.Show.Functions
import qualified Data.Set as Set
import qualified Data.List as List

setTransition :: (Int -> Char -> [Int])  -> [Int] -> Char -> [Int]
setTransition delta [] sigma            = []
setTransition delta xs sigma    = foldl f [] xs
                where f ys q = (delta q sigma) `List.union` ys

Thx for helping

Upvotes: 0

Views: 146

Answers (1)

luqui
luqui

Reputation: 60463

You just had a syntax error:

xs@[x:xs']

should be

xs@(x:xs')

But you don't actually need two cases, because

foldl f b [] = b

so

foldl f [] [] = []

just as your empty list case requires.

In fact, it's quite uncommon to pattern match on [] without pattern matching on (x:xs) and using x and xs -- that's how I knew to think about whether foldl would give you the right answer in both cases. It does happen occasionally, though.

Upvotes: 6

Related Questions