operator-precedencecurry

Specifying default rules in the Curry language: Why and how?


In section 3.5.6 of the Curry tutorial (pdf), we are advised to use default rules to "regain control after a failed search". The following example is given. (For clarity I have added a type signature and curried the input.)

lookup :: k -> [(k,v)] -> Maybe v
lookup key (_++[(key,value)]++_ ) = Just value
lookup’default _ _ = Nothing

I can't get that to compile unless I replace the with a '. Once I do, it behaves like this:

test> test.lookup 1 [(2,3)]
*** No value found!

Question 1: What is the default declaration for?

Why would you need to specify that a particular clause is the default one? Won't it be arrived at one way or another, once the others fail?

Question 2: How is it written? Should it be written at all?

If instead I drop the string 'default:

lookup :: k -> [(k,v)] -> Maybe v
lookup key (_++[(key,value)]++_ ) = Just value
lookup _ _ = Nothing

it behaves as intended:

test> test.lookup 1 [(2,3)]
Nothing
test>

Has the 'default syntax changed since the tutorial was written? Has it been removed altogether?


Solution

  • This is the code you are looking for. Yours was missing the preprocessor directive to allow default rules. And using the wrong quote character.

    -- Use default rules
    {-# OPTIONS_CYMAKE -F --pgmF=currypp --optF=defaultrules #-}
    
    lookup :: k -> [(k,v)] -> Maybe v
    lookup key (_++[(key,value)]++_ ) = Just value
    lookup'default _ _ = Nothing
    
    test_positive = lookup 2 [(2,3)] == Just 3
    test_negative = lookup 1 [(2,3)] == Nothing
    

    A default rule serves various purposes. Regaining control after a failed search is a particularly useful one, since you cannot check with equality whether an expression is a failure.