Haskell: non-exhaustive templates

Tomorrow I train for a test to complete my introduction to functional programming, but there is one thing that I do not understand.

Whenever I have a program like:

test [] = [] test (x:xs) = test (xs) 

What he does is that he takes the first item from the list and continues the rest. Whenever there is only one left, xs should be [] , which in turn should run test [] = [] . But whenever I run this algorithm, I get an error message. Exception: <interactive>:20:5-16: Non-exhaustive patterns in function test.

I could not find a clear explanation on the Internet. Can someone please send me a link where this is explained or explained to me?

+8
haskell ghci
source share
2 answers

The code that you posted in the body of the question contains an exhaustive pattern matching. However, if you try to enter this definition in ghci, you must use a single let statement:

 Prelude> let test [] = [] ; test (x:xs) = test xs 

What you are doing here is wrong. First, you define a non-exhaustive functional test :

 Prelude> let test [] = [] 

And then you define another non-striated function, also called test , which hides the first:

 Prelude> let test (x:xs) = test xs 
+26
source share

It is indeed a very difficult task to test children's programs in the Haskell REPL (GHCi).

Using let not very obvious (especially since it is not required in a separate "script / program").

And sometimes we DO NOT want to create a full-fledged file, but instead experiment with a small function with different β€œcases”.

Another useful approach is to use delimiters :{ and :} to determine the extent of our function.

Let's say we want to try a simple recursive function sum , which can contain a list of numbers. We would then say the following:

 Ξ» > :{ Prelude| sum [] = 0 Prelude| sum (x:xs) = x + sum xs Prelude| :} sum :: Num t => [t] -> t Prelude Ξ» > sum [1..10] 55 it :: (Enum t, Num t) => t 

Pay attention to how nice it is to see the scale of our function now!

Hope this helps. Hooray!

+4
source share

All Articles