3

I know we can use below pattern matching in Haskell:

sum :: (Num a) => [a] -> a  
sum [] = 0  
sum (x:xs) = x + sum xs 

But why can’t we use [x] ++ xs?

sum :: (Num a) => [a] -> a  
sum [] = 0  
sum ([x] ++ xs) = x + sum xs

1 Answer 1

5

You can pattern match using constructors and literals but not functions.

Sign up to request clarification or add additional context in comments.

3 Comments

Is : a constructor?
@4castle Yes. [1,2,3,4] is basically just sugar for 1:2:3:4:[].
Indeed, pattern matching using functions would be nonsense in the general case: what would (\(x++y) -> y++x) "abcde" evaluate to?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.