Changes between Version 21 and Version 22 of ViewPatterns


Ignore:
Timestamp:
Feb 9, 2007 8:01:11 AM (7 years ago)
Author:
simonpj
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ViewPatterns

    v21 v22  
     1;; This buffer is for notes you don't want to save, and for Lisp evaluation. 
     2;; If you want to create a file, visit that file with C-x C-f, 
     3;; then enter the text in that file's own buffer. 
     4 
    15[[PageOutline]] 
    26= View patterns: lightweight views for Haskell = 
     
    272276}}} 
    273277Of course, the argument does not need to be a constant as it is here. 
    274  
    275 The (n+k) patterns can be implemented (with different syntax, of course) with a view function that tests for values greater than or equal to n: 
    276 {{{ 
    277    np :: Num a => a -> a -> Maybe a 
    278    np k n | k <= n    = Just (n-k) 
    279               | otherwise = Nothing 
    280  
    281    f :: Num a => a -> Int 
    282    f (np 10 -> n) = n           -- Matches values >= 10, f a = (a - 10) 
    283    f (np 4  -> n) = 1           -- Matches values >= 4 
    284    f other        = 2 
    285 }}} 
    286278 
    287279With the value input feature, in a sense, patterns become first class. For example, one could pass a pattern as an argument to a function thus: 
     
    402394The majority of the proposals allow nesting. 
    403395 
     396 
     397=== Integration with type classes === 
     398 
     399A view mechanism that integrates nicely with type classes would allow 
     400a single "view" to decompose multiple different data types.  For 
     401example, a view might work on any type in class Num, or in class Sequence. 
     402 
     403A good example is Haskell's existing (n+k) patterns.  Here is how they 
     404can be expressed using the view pattern proposed in this page (with different  
     405syntax, of course): 
     406{{{ 
     407   np :: Num a => a -> a -> Maybe a 
     408   np k n | k <= n    = Just (n-k) 
     409          | otherwise = Nothing 
     410 
     411   g :: Int -> Int 
     412   g (np 3 -> n) = n*2 
     413 
     414   h :: Integer -> Integer 
     415   h (np 9 -> n) = n*2 
     416 
     417   f :: Num a => a -> Int 
     418   f (np 10 -> n) = n           -- Matches values >= 10, f a = (a - 10) 
     419   f (np 4  -> n) = 1           -- Matches values >= 4 
     420   f other        = 2 
     421}}} 
     422Here a single, overloaded view, `np`, can be used  
     423in `g`, and `h` to match against values of different types and, 
     424in `f`'s case, any type in class Num. (Notice too the use of the value  
     425input feature.) 
     426 
     427This feature falls out very nicely from view patterns, but  
     428not from all other proposals. 
    404429 
    405430---------------------------