Re: [Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Roman Cheplyaka
Let's look at it from the operational perspective.

In the GADT case, the set of possibilities is fixed in advance (closed).

Every GADT constructor has a corresponding tag (a small integer) which,
when pattern-matching, tells us which branch to take.

In the data family case, the set of possibilities is open. It is harder
to do robust tagging over all the instances, given that new instances
can be added after the module is compiled.

The right way to do what you want is to use a type class and associate
your data family with that class:

  class C a where
data D a
a :: D a -> a

  instance C Int where
data D Int = DInt Int
a (DInt x) = x

  instance C Bool where
data D Bool = DBool Bool
a (DBool x) = x

Roman

* Alexey Egorov  [2013-04-25 20:29:16+0400]
> 
> Hi,
> suppose that there is following data family:
> > data family D a
> > data instance D Int = DInt Int
> > data instance D Bool = DBool Bool
> it is not possible to match on constructors from different instances:
> > -- type error
> > a :: D a -> a
> > a (DInt x) = x
> > a (DBool x) = x
> however, following works:
> > data G :: * -> * where
> > GInt :: G Int
> > GBool :: G Bool
> >
> > b :: G a -> D a -> a
> > b GInt (DInt x) = x
> > b GBool (DBool x) = x
> The reason why second example works is equality constraints (a ~ Int) and (a 
> ~ Bool) introduced by GADT's constructors, I suppose.
> I'm curious - why data families constructors (such as DInt and DBool) doesn't 
> imply such constraints while typechecking pattern matching?
> Thanks.

> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Francesco Mazzoli
At Fri, 26 Apr 2013 00:20:36 +0400,
Alexey Egorov wrote:
> Yes, my question is about why different instances are different types even if
> they have the same type constructor (D).
> I'm just find it confusing that using GADTs trick it is possible to match on
> different constructors.

See it this way: the two ‘D’s (the GADTs and the data family one) are both type
functions, taking a type and giving you back another type.

In standard Haskell all such type functions return instances of the same data
type (with a set of data constructors you can pattern match on), much like the
‘D’ of the GADTs.  With type/data families the situation changes, and the
returned type can be different depending on the provided type, which is what’s
happening here.

Now the thing you want to do is ultimately write your ‘a’, which as you said
relies on type coercions, but this fact (the ‘GADTs trick’) has nothing to do
with the fact that type families will relate types to different data types.

Francesco

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Alexey Egorov
> Would you expect this to work?
> 
> newtype DInt a = DInt a
> newtype DBool a = DBool a
>
> type family D a
> type instance D Int = DInt Int
> type instance D Bool = DBool Bool
> 
> a :: D a -> a
> a (DInt x) = x
> a (DBool x) = x
> 
> Or even better:
> 
> data family D a
> data instance D Int = DInt1 Int | DInt2 Int
> data instance D Bool = DBool Bool
> 
> a :: D a -> a
> a (DInt1 x) = x
> a (DInt2 x) = x
> a (DBool x) = x

Yes, my question is about why different instances are different types even if 
they have the same type constructor (D).
I'm just find it confusing that using GADTs trick it is possible to match on 
different constructors.

Another confusing thing is that following works:

> data G :: * -> * where
> { GInt :: G Int
> ; GBool :: G Bool }
>
> b :: G a -> D a -> a
> b GInt (DInt x) = x
> b GBool (DBool x) = x

while quite similar doesn't:

> c :: D a -> G a -> a
> c (DInt x) GInt = x
> c (DBool x) GBool = x

However, viewing data families as "type families + per-instance newtype/data 
declaration" is helpful, thank you.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Francesco Mazzoli
At Thu, 25 Apr 2013 19:08:17 +0100,
Francesco Mazzoli wrote:
> Would you expect this to work?
> 
> > newtype DInt a = DInt a
> > newtype DBool a = DBool a
> > 
> > type family D a
> > type instance D Int = DInt Int
> > type instance D Bool = DBool Bool
> > 
> > a :: D a -> a
> > a (DInt x) = x
> > a (DBool x) = x

Or even better:

> data family D a
> data instance D Int = DInt1 Int | DInt2 Int
> data instance D Bool = DBool Bool
> 
> a :: D a -> a
> a (DInt1 x) = x
> a (DInt2 x) = x
> a (DBool x) = x

Francesco

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Francesco Mazzoli
At Thu, 25 Apr 2013 19:08:17 +0100,
Francesco Mazzoli wrote:
> ... ‘DInt :: DInt -> D Int’ and ‘DBool :: DBool -> D Bool’ ...

This should read ‘DInt :: Int -> D Int’ and ‘DBool :: Bool -> D Bool’.

Francesco

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Francesco Mazzoli
At Thu, 25 Apr 2013 20:29:16 +0400,
Alexey Egorov wrote:
> I'm curious - why data families constructors (such as DInt and DBool) doesn't
> imply such constraints while typechecking pattern matching?

I think you are misunderstanding what data families do.  ‘DInt :: DInt -> D Int’
and ‘DBool :: DBool -> D Bool’ are two data constructors for *different* data
types (namely, ‘D Int’ and ‘D Bool’).  The type family ‘D :: * -> *’ relates
types to said distinct data types.

On the other hand the type constructor ‘D :: * -> *’ parametrises a *single*
data type over another type—the fact that the parameter can be constrained
depending on the data constructor doesn’t really matter here.

Would you expect this to work?

> newtype DInt a = DInt a
> newtype DBool a = DBool a
> 
> type family D a
> type instance D Int = DInt Int
> type instance D Bool = DBool Bool
> 
> a :: D a -> a
> a (DInt x) = x
> a (DBool x) = x

Francesco

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] pattern matching on data families constructors

2013-04-25 Thread Alexey Egorov

Hi,
suppose that there is following data family:
> data family D a
> data instance D Int = DInt Int
> data instance D Bool = DBool Bool
it is not possible to match on constructors from different instances:
> -- type error
> a :: D a -> a
> a (DInt x) = x
> a (DBool x) = x
however, following works:
> data G :: * -> * where
> GInt :: G Int
> GBool :: G Bool
>
> b :: G a -> D a -> a
> b GInt (DInt x) = x
> b GBool (DBool x) = x
The reason why second example works is equality constraints (a ~ Int) and (a ~ 
Bool) introduced by GADT's constructors, I suppose.
I'm curious - why data families constructors (such as DInt and DBool) doesn't 
imply such constraints while typechecking pattern matching?
Thanks.___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with singletons

2013-03-27 Thread Paul Brauner
Very helpful, thanks! I may come back with more singleton/type families
questions :)


On Tue, Mar 26, 2013 at 6:41 PM, Richard Eisenberg wrote:

> Hello Paul,
>
> > - Forwarded message from Paul Brauner  -
>
> 
>
> >   - is a ~ ('CC ('Left 'CA)) a consequence of the definitions of SCC,
> >   SLeft, ... (in which case GHC could infer it but for some reason can't)
> >   - or are these pattern + definitions not sufficient to prove that a
> >   ~ ('CC ('Left 'CA)) no matter what?
>
> The first one. GHC can deduce that (a ~ ('CC ('Left b))), for some fresh
> variable (b :: TA), but it can't yet take the next step and decide that,
> because TA has only one constructor, b must in fact be 'CA. In type-theory
> lingo, this deduction is called eta-expansion. There have been on-and-off
> debates about how best to add this sort of eta-expansion into GHC, but all
> seem to agree that it's not totally straightforward. For example, see GHC
> bug #7259. There's a non-negligible chance I will be taking a closer look
> into this at some point, but not for a few months, so don't hold your
> breath. I'm not aware of anyone else currently focusing on this problem
> either, I'm afraid.
>
> I'm glad you're finding use in the singletons package! Let me know if I
> can be of further help.
>
> Richard
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with singletons

2013-03-26 Thread Richard Eisenberg
Hello Paul,

> - Forwarded message from Paul Brauner  -



>   - is a ~ ('CC ('Left 'CA)) a consequence of the definitions of SCC,
>   SLeft, ... (in which case GHC could infer it but for some reason can't)
>   - or are these pattern + definitions not sufficient to prove that a
>   ~ ('CC ('Left 'CA)) no matter what?

The first one. GHC can deduce that (a ~ ('CC ('Left b))), for some fresh 
variable (b :: TA), but it can't yet take the next step and decide that, 
because TA has only one constructor, b must in fact be 'CA. In type-theory 
lingo, this deduction is called eta-expansion. There have been on-and-off 
debates about how best to add this sort of eta-expansion into GHC, but all seem 
to agree that it's not totally straightforward. For example, see GHC bug #7259. 
There's a non-negligible chance I will be taking a closer look into this at 
some point, but not for a few months, so don't hold your breath. I'm not aware 
of anyone else currently focusing on this problem either, I'm afraid.

I'm glad you're finding use in the singletons package! Let me know if I can be 
of further help.

Richard
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching with singletons

2013-03-25 Thread Paul Brauner
Hello,

the following programs seems to hit either some limitation of GHC or maybe
I'm just missing something and it behaves the intended way.

{-# LANGUAGE TemplateHaskell, TypeFamilies, DataKinds, GADTs #-}

module Test where

import Data.Singletons

data TA = CA
data TB = CB
data TC = CC (Either TA TB)

$(genSingletons [''TA, ''TB, ''TC])

type family Output (x :: TC) :: *
type instance Output ('CC ('Left  'CA)) = Int
type instance Output ('CC ('Right 'CB)) = String

f :: Sing (a :: TC) -> Output a
f (SCC (SLeft SCA)) = 1

g :: Sing (a :: TC) -> Output a
g (SCC (SLeft _)) = 1


Function f typechecks as expected. Function g fails to typecheck with the
following error.

Could not deduce (Num (Output ('CC ('Left TA TB n0
  arising from the literal `1'
from the context (a ~ 'CC n, SingRep (Either TA TB) n)
  bound by a pattern with constructor
 SCC :: forall (a_a37R :: TC) (n_a37S :: Either TA TB).
(a_a37R ~ 'CC n_a37S, SingRep (Either TA TB)
n_a37S) =>
Sing (Either TA TB) n_a37S -> Sing TC a_a37R,
   in an equation for `g'
  at Test.hs:21:4-16
or from (n ~ 'Left TA TB n0,
 SingRep TA n0,
 SingKind TA ('KindParam TA))
  bound by a pattern with constructor
 SLeft :: forall (a0 :: BOX)
 (b0 :: BOX)
 (a1 :: Either a0 b0)
 (n0 :: a0).
  (a1 ~ 'Left a0 b0 n0, SingRep a0 n0,
   SingKind a0 ('KindParam a0)) =>
  Sing a0 n0 -> Sing (Either a0 b0) a1,
   in an equation for `g'
  at Test.hs:21:9-15
Possible fix:
  add an instance declaration for
  (Num (Output ('CC ('Left TA TB n0
In the expression: 1
In an equation for `g': g (SCC (SLeft _)) = 1


I would expect that a ~ ('CC ('Left 'CA)) in the right hand-side of g (SCC
(SLeft _)) = 1 since SLeft's argument is necessarily of type STA, whose
sole inhabitant is SA.

Now I understand (looking at -ddump-slices, the singletons' library paper
and the error message) that the definition of SCC and SLeft
don't immediately imply what I just wrote above. So my question is: in the
right hand-side of g (SCC (SLeft _)) = 1,

   - is a ~ ('CC ('Left 'CA)) a consequence of the definitions of SCC,
   SLeft, ... (in which case GHC could infer it but for some reason can't)
   - or are these pattern + definitions not sufficient to prove that a
   ~ ('CC ('Left 'CA)) no matter what?

Cheers,
Paul
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching: multi constructors to same branch

2012-09-11 Thread Michael Sloan
I've seen this asked before, and I think some languages support it (ML
maybe?).  One way to do this is with view patterns:

g f C = [f C]
g f (getVN -> (v, n)) = f v : g f n

getVN v@(A _ n) = (v, n)
getVN v@(B _ n) = (v, n)

(I changed the recursive call to g - figured you meant passing along f)

If you need to still have match clauses after that, for falling
through when it's not something that getVN matches, then have it yield
a Maybe, and match on Just.

-Michael

On Tue, Sep 11, 2012 at 9:43 AM, Thiago Negri  wrote:
> Is it possible to capture more than one constructor in a single
> pattern matching?
> I mean, is it possible to generalize the following pattern matching of
> A and B to a single branch?
>
> g f C = [f C]
> g f v@(A _ n) = f v : g n
> g f v@(B _ n) = f v : g n
>
> For example:
>
> g f C = [f C]
> g f v@(A|B _ n) = f v : g n
>
> Or:
>
> g f v =
> case v of
> C -> [f C]
> A|B -> f v : g (n v)
>
>
> Thanks.
>
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching: multi constructors to same branch

2012-09-11 Thread Thiago Negri
Is it possible to capture more than one constructor in a single
pattern matching?
I mean, is it possible to generalize the following pattern matching of
A and B to a single branch?

g f C = [f C]
g f v@(A _ n) = f v : g n
g f v@(B _ n) = f v : g n

For example:

g f C = [f C]
g f v@(A|B _ n) = f v : g n

Or:

g f v =
case v of
C -> [f C]
A|B -> f v : g (n v)


Thanks.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching vs if-then-else

2012-08-12 Thread Gregory Collins
On Sun, Aug 12, 2012 at 1:30 PM, Maarten Faddegon <
haskell-c...@maartenfaddegon.nl> wrote:
>
> = if-- All stmts use the same lcv
>test_lcv == init_lcv
> && test_lcv == update_lcv
> && test_lcv == update_lcv'
> -- And the lcv is not updated in the body
>

This part of the conditional can be written more succinctly as:

all (== test_lcv) [init_lcv, update_lcv, update_lcv']


Re: the if statement, you can also use guard syntax.

G
-- 
Gregory Collins 
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] pattern matching vs if-then-else

2012-08-12 Thread Maarten Faddegon

Hi there,

I am writing a toy compiler in Haskell to further my skills in 
functional programming. One of the functions I wrote is to determine the 
iteration count of a loop. I have a number of different test that I want 
to do and I find myself now testing some of these using pattern matching 
and some properties using an if-then-else construction. I do not 
consider this very pretty.


My question is: are there guidelines of when to use pattern matching and 
when to use if-then-else?


Snippet of the function I mentioned:

---8<--- 


itercount (ForLoop
[ ( Assignment update_lcv
(Op2 "+" (Content update_lcv') update_expr)
  )
]
[(Assignment init_lcv init_expr)]
(TestStmt (Op2 "<" (Content test_lcv) test_expr))
bodyblock)
= if-- All stmts use the same lcv
   test_lcv == init_lcv
&& test_lcv == update_lcv
&& test_lcv == update_lcv'
-- And the lcv is not updated in the body
&& intersect [test_lcv] (blockkills bodyblock) == []
then Just $ simple_itercount init_expr test_expr 
update_expr

else Nothing
itercount _ = Nothing
---8<--- 



Thanks,
  Maarten

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern-matching & substitution for haskell-src-exts?

2012-01-18 Thread Joachim Breitner
Hi,

Am Mittwoch, den 18.01.2012, 12:05 -0800 schrieb Conal Elliott:
> Has anyone implemented pattern-matching & substitution for
> haskell-src-exts?  - Conal

without checking the code, I believe that hlint does exactly that; it
takes rules (given as Haskell code), matches them as patterns against
the real code and substitutes the matched parts in the right side of the
rule.

Greetings,
Joachim

-- 
Joachim "nomeata" Breitner
  m...@joachim-breitner.de  |  nome...@debian.org  |  GPG: 0x4743206C
  xmpp: nome...@joachim-breitner.de | http://www.joachim-breitner.de/



signature.asc
Description: This is a digitally signed message part
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern-matching & substitution for haskell-src-exts?

2012-01-18 Thread Gwern Branwen
On Wed, Jan 18, 2012 at 3:05 PM, Conal Elliott  wrote:
> Has anyone implemented pattern-matching & substitution for
> haskell-src-exts?  - Conal

I don't know what exactly you are looking for, but I remember banging
together a function-name search script using haskell-src-exts and
'find' last summer, which pattern-matches, looking for use of
particular function-names. Presumably you could change
`functionSearch` to not call `length` but instead replace the matched
function with another function and then write out the modules? Well,
maybe the source will be helpful, maybe not:

import System.Environment (getArgs)
import Language.Haskell.Exts
import qualified Data.Foldable as F (concat)
import Data.Generics.Uniplate.Data
-- import Debug.Trace

main :: IO ()
main = do (func:_) <- getArgs
  args <- fmap lines $ getContents
  mapM_ (checkAndPrint func) args

checkAndPrint :: String -> FilePath -> IO ()
checkAndPrint fn fs = do print fs
 x <- readFile fs
 let exts = F.concat $ readExtensions x
 let parsed = parseFileContentsWithMode
(defaultParseMode { fixities = fixes, extensions = exts }) x
 case parsed of
  ParseFailed _ _ -> (return ())
  ParseOk a -> functionSearch fn a
 return ()

-- the default fixities augmented with everything necessary to parse my corpus
fixes :: Maybe [Fixity]
fixes = Just $ baseFixities ++ infixr_ 0 ["==>"]

functionSearch :: String -> Module -> IO ()
functionSearch fun md = do
  let x = length [ () | Var (UnQual (Ident a)) <- universeBi md, a == fun]
  putStrLn $ "Found " ++ show x ++ " occurences of function " ++ fun

-- 
gwern
http://www.gwern.net

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern-matching & substitution for haskell-src-exts?

2012-01-18 Thread Conal Elliott
Has anyone implemented pattern-matching & substitution for
haskell-src-exts?  - Conal
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching instead of prelude.head

2011-09-16 Thread Evan Laforge
On Fri, Sep 16, 2011 at 2:34 PM, Albert Y. C. Lai  wrote:
> On 11-09-15 10:24 PM, Michael Litchard wrote:
>>
>> Someone commented on StackOverflow that pattern matching the first
>> element of a list was preferable to head. This makes sense
>> intuitively. Could someone articulate the reason why this is true?
>
> if null s then e0 else ...(head s)...(tail s)...
>
> is a clumsy way to say
>
> case s of
>  [] -> e0
>  h:t -> ...h...t...
>
> The clumsy way is more familiar because it is popularized by lisp. It is the
> way in lisp because lisp is old.

I have 'head :: [a] -> Maybe a' along with tail, maximum/minimum and
various other prelude functions that, IMHO, shouldn't have been
partial.  I agree case is often better, but sometimes Maybe is
convenient, e.g. when composing with other Maybes.  And I can pass it
easily to 'maybe', but then I suppose someone is going to say I should
define 'b -> (a -> [a] -> b) -> [a] -> b' and use that directly :)

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching instead of prelude.head

2011-09-16 Thread Albert Y. C. Lai

On 11-09-15 10:24 PM, Michael Litchard wrote:

Someone commented on StackOverflow that pattern matching the first
element of a list was preferable to head. This makes sense
intuitively. Could someone articulate the reason why this is true?


if null s then e0 else ...(head s)...(tail s)...

is a clumsy way to say

case s of
  [] -> e0
  h:t -> ...h...t...

The clumsy way is more familiar because it is popularized by lisp. It is 
the way in lisp because lisp is old.


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching instead of prelude.head

2011-09-15 Thread wren ng thornton

On 9/15/11 10:24 PM, Michael Litchard wrote:

Someone commented on StackOverflow that pattern matching the first
element of a list was preferable to head. This makes sense
intuitively. Could someone articulate the reason why this is true?


(1) If you call (head xs) you are assuming that xs is non-empty. If xs 
is empty, then it will throw an exception. Which is a major issue 
because tracing down these exceptions is a headache for everyone 
involved. Whereas, if you do (case xs of [] -> ...; x:xs' -> ...) you 
explicitly handle the case of xs being empty. This also applies to 
things like tail and fromJust.



(2) Also, even if you know xs is non-empty because you called (null xs) 
or the like, you can do the case match once and use the results 
everywhere. Whereas, using head and tail means doing a case match every 
time they're called. This is an efficiency issue, and also applies to 
functions which won't throw exceptions: like fst and snd, instead of 
pattern matching the tuple.


--
Live well,
~wren

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching instead of prelude.head

2011-09-15 Thread Lyndon Maydwell
Pattern matching will warn you if you neglect to consider the empty list.

On Fri, Sep 16, 2011 at 10:24 AM, Michael Litchard  wrote:
> Someone commented on StackOverflow that pattern matching the first
> element of a list was preferable to head. This makes sense
> intuitively. Could someone articulate the reason why this is true?
>
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] pattern matching instead of prelude.head

2011-09-15 Thread Michael Litchard
Someone commented on StackOverflow that pattern matching the first
element of a list was preferable to head. This makes sense
intuitively. Could someone articulate the reason why this is true?

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching on lazy bytestrings: how does it work?

2011-04-23 Thread Helgi Kristvin Sigurbjarnarson
On Fri, Apr 22, 2011 at 11:52:32PM -0700, Tom Brow wrote:
> I noticed today that I can pattern match against lazy bytestrings when using
> the OverloadedStrings extension:
[..]
> Given that pattern matching is based on data constructors, how is it possible
> that (Chunk "abc Empty) and (Chunk "a" (Chunk "bc" Empty)) match the same
> pattern?
> 
> Tom
> 

According to the haskell report[1] string literals use the overloaded (==)
for pattern matching.

Matching a numeric, character, or string literal pattern k against a
value v succeeds if v == k, where == is overloaded based on the type of
the pattern. The match diverges if this test diverges.

[1]: http://www.haskell.org/onlinereport/exps.html#sect3.17.2

-- 
Helgi Kristvin Sigurbjarnarson 


pgpu1kqNpXfhn.pgp
Description: PGP signature
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching on lazy bytestrings: how does it work?

2011-04-23 Thread Stephen Tetley
Surely `fromChunks` is making the both lines in the code snippet the same?

Also, in your last sentence I think you've miscalculated the shape of
the initial input.

Best wishes

Stephen

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching on lazy bytestrings: how does it work?

2011-04-22 Thread Tom Brow
I noticed today that I can pattern match against lazy bytestrings when using
the OverloadedStrings extension:

import Data.ByteString.Char8 ()
>
> import Data.ByteString.Lazy.Char8
>
>
>> f :: ByteString -> Bool
>
> f "abc" = True
>
> f _ = False
>
>
>> main = do
>
> print $ f $ fromChunks ["abc"]
>
> print $ f $ fromChunks ["a","bc"]
>
>
When I run the above, I get:

True
>
> True
>
>
Given that pattern matching is based on data constructors, how is it
possible that (Chunk "abc Empty) and (Chunk "a" (Chunk "bc" Empty)) match
the same pattern?

Tom
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching, and bugs

2009-12-19 Thread wren ng thornton

Ketil Malde wrote:

András Mocsáry  writes:

Now we have a problem, which is most generally fixed in these ways:
C-like:

switch ( x )
{
Case 0:
  "Unchecked"
Case 1:
  "Checked"
Case 2:
  "Unknown"
Default:
  "Nothing"
}


This is not a fix, this is a workaround for a design bug, namely that
x is of a type that allows meaningless data.


Indeed. In C-like languages it is common practice to use integers to 
mean just about anything. Often there are fewer of "anything" than there 
are integers, and so hacks like this are necessary to work around the 
ensuing problems. But ultimately, this is a *type error*.


The proper response, in Haskell, to type errors like this is not to add 
hacks catching bad values, but rather to change the types so that bad 
values cannot be constructed. As a few others have mentioned, rather 
than using an integer, you should define a new type like:


data X = Unchecked | Checked | Unknown

and then require that x is of type X. Thus the pattern-checker can 
verify that all possible values of x will match some case option.


The reason Haskell (or other typed functional languages) allow proving 
correctness so much easier than other languages is because we create new 
types which correctly and precisely match the set of values we want to 
belong to that type[1]. By pushing as much of the correctness logic as 
possible up into the type layer, this frees us from needing to check 
things at the term layer since the type-checker can capture type errors 
automatically. But it can't catch things we haven't told it are errors.



[1] For some complex sets of values this isn't possible with Haskell's 
type system, which is one of the reasons for the recent interest in 
dependently typed languages. However, for most familiar sets of values 
(and quite a few unfamiliar ones) Haskell's type system is more than enough.


--
Live well,
~wren
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching, and bugs

2009-12-18 Thread Ketil Malde
András Mocsáry  writes:

> Now we have a problem, which is most generally fixed in these ways:
> C-like:

>> switch ( x )
>
> {
>
> Case 0:
>
>   "Unchecked"
>
> Case 1:
>
>   "Checked"
>
> Case 2:
>
>   "Unknown"
>
> Default:
>
>   "Nothing"
>
> }

This is not a fix, this is a workaround for a design bug, namely that
x is of a type that allows meaningless data.

> Haskell like:
>
> switch 1 =  "Unchecked"
>
> switch 2 =  "Checked"
>
> switch 3 =  "Unknown"
>
> switch x =  "Nothing"

> These general ways really avoid this particular crash, but does something
> real bad to the code in my opinion.

Yes.  The type of the parameter should be designed so that it only allows
the three legal values.  Using an integer value when there are only
three real options is bad design.

> *1. The bad data we got as 'x', could have came from an another part of our
> very program, which is the REAL CAUSE of the crash, but we successfully hide
> it.*

> 2. The bad data we got as 'x', could also could have come form a real
> word object, we have underestimated, or which changed in the meantime.

I think these two are the same - in case 2, it is the parser that
should produce an error.  If it may fail, there's a plethora of
solutions, for instance, wrapping the result in a Maybe.  This will force
users of the data to take failure into account.

> 3. This 'x' could have been corrupted over a network, or by 'mingling' or by
> other faulty software or something.

I'm not really sure how a Haskell program would react to memory errors
or similar.  Badly, I expect.

> I would like to have a way for Haskell, not to crash, when my coders write
> pattern matching without the above mentioned general case.

I think this just encourages sloppy programming, and as has been pointed
out, you can catch the exception if you think you can deal with it
reasonably. 

GHC warns you if you do incomplete pattern matching, and I think it's a
good idea to adhere to the warnings.

> In my case for server software, where network corrupted data,
> ( and data which has been 'tampered with' by some 'good guy' who think he's
> robin hood if he can 'hack' the server ) is an every day reality.

I like the Erlang approach: let it (the subsystem) crash, catch the
exception, report it, and restart.

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching, and bugs

2009-12-18 Thread Serguey Zefirov
> I would like to have a way for Haskell, not to crash, when my coders write
> pattern matching without the above mentioned general case.
> Like having the compiler auto-include those general cases for us,
> but when those cases got hit, then instead of crashing, it should report
> some error on stdout or stderr.
> (It would be even nicer if it cold have been traced.)

You should not wait for Haskell prime. What you are asking is already
in libraries: 
http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Control-Exception.html
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching, and bugs

2009-12-18 Thread Jochem Berndsen
András Mocsáry wrote:
> *My concern*
> is about predictable failure of sw written in Haskell.
> To illustrate it let's see a Haskell pattern matching example:

> And in Haskell pattern matching:
> 
> switch 1 =  "Unchecked"
> 
> switch 2 =  "Checked"
> 
> switch 3 =  "Unknown"
> 
> 
> Let's say, these are clearly defined states of some objects.
> Then let's say something unexpected happens: x gets something else than 0 1
> 2.
> Now we have a problem, which is most generally fixed in these ways:
> 
> switch 1 =  "Unchecked"
> 
> switch 2 =  "Checked"
> 
> switch 3 =  "Unknown"
> 
> switch x =  "Nothing"
> 
> These general ways really avoid this particular crash, but does something
> real bad to the code in my opinion.

Agreed. The real cause of the problem is that the programmer didn't
prove that x is in {1,2,3} when calling switch.

> Below are some cases x can go wrong:
> *1. The bad data we got as 'x', could have came from an another part of our
> very program, which is the REAL CAUSE of the crash, but we successfully hide
> it.*
> *
> Which makes it harder to fix later, and thus eventually means the death of
> the software product. Eventually someone has to rewrite it.
> Which is economically bad for the company, since rewriting implies increased
> costs.

Yes.

> 2. The bad data we got as 'x', could also could have come form a real
> word object,
> we have underestimated, or which changed in the meantime.

You should not assume that your input is correct in fault-tolerant programs.

> 3. This 'x' could have been corrupted over a network, or by 'mingling' or by
> other faulty software or something.

Unlikely. There is nothing you can do about this, though.


> Point 1:
> If we allow ourself such general bugfixes, we eventually kill the ability of
> the project to 'evolve'.
> 
> Point 2:
> Programmers eventually take up such 'arguably bad' habits, thus making
> harder to find such bugs.
> 
> Thus it would be wiser to tell my people to never write Default cases, and
> such general pattern matching cases.

It is a better idea to use the type system to prevent this kind of bugs.
In this particular case, it's better to try to have a datatype like
data X = One | Two | Three

> *
> Which leads to the very reason I wrote to you:
> 
> I want to propose this for Haskell prime:
> 
> I would like to have a way for Haskell, not to crash, when my coders write
> pattern matching without the above mentioned general case.
> Like having the compiler auto-include those general cases for us,
> but when those cases got hit, then* instead of crashing*, it *should **report
> some error* on *stdout *or *stderr*.
> (It would be even nicer if it cold have been traced.)

And, how would it continue?
Suppose that we have the function
head :: [a] -> a
head (x:_) = x

What would you propose that would happen if I call head [] ? Print an
error on stderr, say, but what should it return? Surely it cannot make
an value of type "a" out of thin air?

Nowadays, head [] crashes the program, and you get an error message to
standard error.

> This is very much like warning suppression, just that it's crash
> suppression, with the need of a report message of course.

This is already possible with exception handling.

> *I would like to hear your opinion on this.*

I don't think it can be implemented in a sane way, or that it's a good
idea to suppress this silently, when an explicit solution already exists.

> I also think, that there are many similar cases in haskell, where not
> crashing, just error reporting would be way more beneficial.
> In my case for server software, where network corrupted data,
> ( and data which has been 'tampered with' by some 'good guy' who think he's
> robin hood if he can 'hack' the server )
> is an every day reality.

You should validate your data in any case. You may even turn a DoS
attack into a "real" security problem with your "solution".

Cheers, Jochem

-- 
Jochem Berndsen | joc...@functor.nl | joc...@牛在田里.com
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching, and bugs

2009-12-18 Thread András Mocsáry
Hello,
I was advised respectfully to post my query here.
Please, read the whole letter before you do anything, because I tried to
construct the problem step by step.
Also keep in mind, that the problem I query here is more general, and
similar cases occur elsewhere, not just in this particular example I present
below.

*Intro story* ( Skip if you are in a hurry )
I'm participating in several open-source server development projects, most
of them are written in C, and some of them have C++ code hidden here and
there.
These programs, are developed by many, and by many ways, and so, more often
than not it is very hard to determine the 'real cause of bugs'.
This almost always leads to 'bugfixes' which 'treat the crash'. Sometimes
they are a few lines of extra checks, like IFs.
Sometimes they are complex, and even surprisingly clever hacks.
Thus understanding the 'code' of them is challenging, but the end result is
a pile of ... hacks fixing bugs fixing hacks fixing bug, which also were put
there to fix yet another bugs.
+
When I started to learn functional programming, I was told, that
the correctness of a functional program can be proved a lot more easily, in
fact in a straight mathematical way.
+
*My concern*
is about predictable failure of sw written in Haskell.
To illustrate it let's see a Haskell pattern matching example:

Let's say I have defined some states my object could be in, and I did in a
switch in some C-like language:

> switch ( x )

{

Case 0:

  "Unchecked"

Case 1:

  "Checked"

Case 2:

  "Unknown"

}


And in Haskell pattern matching:

switch 1 =  "Unchecked"

switch 2 =  "Checked"

switch 3 =  "Unknown"


Let's say, these are clearly defined states of some objects.
Then let's say something unexpected happens: x gets something else than 0 1
2.
Now we have a problem, which is most generally fixed in these ways:
C-like:

> switch ( x )

{

Case 0:

  "Unchecked"

Case 1:

  "Checked"

Case 2:

  "Unknown"

Default:

  "Nothing"

}


Haskell like:

switch 1 =  "Unchecked"

switch 2 =  "Checked"

switch 3 =  "Unknown"

switch x =  "Nothing"

These general ways really avoid this particular crash, but does something
real bad to the code in my opinion.

Below are some cases x can go wrong:
*1. The bad data we got as 'x', could have came from an another part of our
very program, which is the REAL CAUSE of the crash, but we successfully hide
it.*
*
Which makes it harder to fix later, and thus eventually means the death of
the software product. Eventually someone has to rewrite it.
Which is economically bad for the company, since rewriting implies increased
costs.

2. The bad data we got as 'x', could also could have come form a real
word object,
we have underestimated, or which changed in the meantime.

3. This 'x' could have been corrupted over a network, or by 'mingling' or by
other faulty software or something.

Point 1:
If we allow ourself such general bugfixes, we eventually kill the ability of
the project to 'evolve'.

Point 2:
Programmers eventually take up such 'arguably bad' habits, thus making
harder to find such bugs.

Thus it would be wiser to tell my people to never write Default cases, and
such general pattern matching cases.

*
Which leads to the very reason I wrote to you:

I want to propose this for Haskell prime:

I would like to have a way for Haskell, not to crash, when my coders write
pattern matching without the above mentioned general case.
Like having the compiler auto-include those general cases for us,
but when those cases got hit, then* instead of crashing*, it *should **report
some error* on *stdout *or *stderr*.
(It would be even nicer if it cold have been traced.)


This is very much like warning suppression, just that it's crash
suppression, with the need of a report message of course.

*I would like to hear your opinion on this.*

I also think, that there are many similar cases in haskell, where not
crashing, just error reporting would be way more beneficial.
In my case for server software, where network corrupted data,
( and data which has been 'tampered with' by some 'good guy' who think he's
robin hood if he can 'hack' the server )
is an every day reality.


Thanks for your time reading my 'storm'.

Greets,

Andrew
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-13 Thread Casey Hawthorne
Thank you to all who replied, very instructive.
--
Regards,
Casey
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-13 Thread Daniel Fischer
Am Freitag 13 November 2009 11:05:15 schrieb Andrew Coppin:
> Colin Paul Adams wrote:
> > If I had a dollar for every time I've written something like
> >
> > Andrew>  case msg of eVENT_QUIT -> ...  eVENT_POST -> ...
> > Andrew> eVENT_RESIZE -> ...
> >
> > Andrew> and spent an hour trying to figure out why the messages
> > Andrew> aren't being processed right... ;-)
> >
> > So why aren't they?
>
> Because what I *should* have written is
>
>   case msg of
> _ | msg == eVENT_QUIT -> ...
>
>| msg == eVENT_POST -> ...
>| msg == eVENT_RESIZE -> ...
>
> which is something quite different.
>
> (And, entertainingly, because the incorrect version is perfectly valid
> source code, no compiler errors or warnings...)

It yells "overlapping patterns" -- you do pass -Wall, don't you?



___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-13 Thread Malcolm Wallace
(And, entertainingly, because the incorrect version is perfectly  
valid source code, no compiler errors or warnings...)


If you actually turn on compiler warnings (-Wall), I think you will  
see something like


andrew.hs:10:10:
Warning: This binding for `eVENT_QUIT' shadows the existing binding
   defined at EventLog.hs:43:0
 In a case alternative

and so forth, for every incorrect alternative.

Regards,
Malcolm

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-13 Thread Andrew Coppin

Colin Paul Adams wrote:

If I had a dollar for every time I've written something like

Andrew>  case msg of eVENT_QUIT -> ...  eVENT_POST -> ...
Andrew> eVENT_RESIZE -> ...

Andrew> and spent an hour trying to figure out why the messages
Andrew> aren't being processed right... ;-)

So why aren't they?
  


Because what I *should* have written is

 case msg of
   _ | msg == eVENT_QUIT -> ...
  | msg == eVENT_POST -> ...
  | msg == eVENT_RESIZE -> ...

which is something quite different.

(And, entertainingly, because the incorrect version is perfectly valid 
source code, no compiler errors or warnings...)


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-13 Thread Colin Paul Adams
> "Andrew" == Andrew Coppin  writes:

Andrew> Casey Hawthorne wrote:
>> Why in a pattern match like
>> 
>> score (1 3) = 7
>> 
>> can I not have
>> 
>> sizeMax = 3
>> 
>> score (1 sizeMax) = 7
>> 

If I had a dollar for every time I've written something like

Andrew>  case msg of eVENT_QUIT -> ...  eVENT_POST -> ...
Andrew> eVENT_RESIZE -> ...

Andrew> and spent an hour trying to figure out why the messages
Andrew> aren't being processed right... ;-)

So why aren't they?


-- 
Colin Adams
Preston Lancashire
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-13 Thread Andrew Coppin

Casey Hawthorne wrote:

Why in a pattern match like

score (1 3) = 7

can I not have

sizeMax = 3

score (1 sizeMax) = 7
  


If I had a dollar for every time I've written something like

 case msg of
   eVENT_QUIT -> ...
   eVENT_POST -> ...
   eVENT_RESIZE -> ...

and spent an hour trying to figure out why the messages aren't being 
processed right... ;-)


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-12 Thread John Dorsey
Casey,

> Why in a pattern match like
> 
> score (1 3) = 7

You probably mean
> score 1 3 = 7

which applies the function 'score' to two arguments.  With the parentheses,
it looks like an application of '1' to the argument '3'.  But to answer your
actual question...

> can I not have
> 
> sizeMax = 3
> 
> score (1 sizeMax) = 7

When a variable name (such as 'sizeMax') appears in a pattern, it gets bound
there.  This is useful so you can refer to the variable on the right hand
side, as in:

successor x = x + 1

How would the compiler know whether to bind the variable (what actually
happens), or match against the value represented by some earlier binding
(what you're asking for)?

What if the type of that second argument doesn't have a defined equality
operation?

There might be some reasonable way to do it, but I suspect it would be
fragile and error-prone, at best.  So it's always a new binding.  It's easy
enough to work around:

score 1 x | x == sizeMax = 7

Regards,
John

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern Matching

2009-11-12 Thread Brandon S. Allbery KF8NH

On Nov 12, 2009, at 21:15 , Casey Hawthorne wrote:

Why in a pattern match like

score (1 3) = 7

can I not have

sizeMax = 3

score (1 sizeMax) = 7



Because it's a pattern, and when you introduce a symbol you are  
inviting the pattern match to bind what it matched to that name for  
use within the function.  (Ordinary arguments are a trivial case of  
this.)


Or, by example:

> score (1 sizeMax) = (expression using sizeMax)

The normal way to do what you want is guards:

> score (1 x) | x == sizeMax = 7 -- you can pronounce the "|" as  
"such that"


--
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allb...@kf8nh.com
system administrator [openafs,heimdal,too many hats] allb...@ece.cmu.edu
electrical and computer engineering, carnegie mellon universityKF8NH




PGP.sig
Description: This is a digitally signed message part
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern Matching

2009-11-12 Thread Casey Hawthorne
Why in a pattern match like

score (1 3) = 7

can I not have

sizeMax = 3

score (1 sizeMax) = 7

--
Regards,
Casey
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with where free variables can be used more than once

2009-07-26 Thread Christopher Done
Well, as I said previously, in reply to Wolfgang, forget the (==) and/or Eq
instance; just use the constructors. You don't need an Eq instance for them.

You have the expression:

foo (a,b)

and the definition:

foo (X,X) = ..

Let's say the predicate for checking that the value of `a' matches X is
Predicate A.

Likewise, for

foo (x,x) = ...

We can use Predicate A to compare `a' and `b', for determining whether the
(x,x) pattern succeeds.

2009/7/18 Richard O'Keefe 

>
> On Jul 18, 2009, at 6:35 AM, Christopher Done wrote:
> [non-linear patterns]
>
> This kind of matching is provided in Prolog and Erlang.
> Neither of them lets the user define equality.
>
> We find the same issue with
>   n+k   patterns   (e.g., n+1 as a pattern)
>   l++r  patterns   (e.g., "prefix"++tail)
>   (x,x) patterns (hidden ==)
>
> In each case, the question is "what if the Prelude's version
> of the explicit or implied function is not in scope?"  (For
> n+k patterns, is the relevant function "+" or is it ">=" and "-"?
> For l++r patterns, is it "++", or "null", "head", and "tail"?)
>
> My preferred answer would be to say "the only functions in
> scope in a pattern are constructors; these aren't functions,
> they're syntax, and they always relate to the Prelude."
>
> The Haskell' community's preferred answer seems to be
> "avoid the question, ban the lot of them."
>
> It's fair to say that any such pattern _can_ be rewritten to
> something Haskell can handle; it's also fair to say that the
> result is often less readable, but that a rewrite may reduce
> the pain.
>
>
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with where free variables can be used more than once

2009-07-23 Thread wren ng thornton

Richard O'Keefe wrote:

On Jul 18, 2009, at 6:35 AM, Christopher Done wrote:
[non-linear patterns]

This kind of matching is provided in Prolog and Erlang.
Neither of them lets the user define equality.

We find the same issue with
   n+k patterns(e.g., n+1 as a pattern)
   l++r  patterns(e.g., "prefix"++tail)
   (x,x) patterns (hidden ==)

In each case, the question is "what if the Prelude's version
of the explicit or implied function is not in scope?"  (For
n+k patterns, is the relevant function "+" or is it ">=" and "-"?
For l++r patterns, is it "++", or "null", "head", and "tail"?)

My preferred answer would be to say "the only functions in
scope in a pattern are constructors; these aren't functions,
they're syntax, and they always relate to the Prelude."

The Haskell' community's preferred answer seems to be
"avoid the question, ban the lot of them."

It's fair to say that any such pattern _can_ be rewritten to
something Haskell can handle; it's also fair to say that the
result is often less readable, but that a rewrite may reduce
the pain.



Also, there was a big long thread about non-linear patterns a couple 
months back. The conclusion of which was "yes we could, but it would 
cause civil war". Some like that kind of sugar, some strongly dislike 
it, some wonder where it will all end, and some say just go use Curry 
already :3


--
Live well,
~wren
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with where free variables can be used more than once

2009-07-17 Thread Richard O'Keefe


On Jul 18, 2009, at 6:35 AM, Christopher Done wrote:
[non-linear patterns]

This kind of matching is provided in Prolog and Erlang.
Neither of them lets the user define equality.

We find the same issue with
   n+k   patterns   (e.g., n+1 as a pattern)
   l++r  patterns   (e.g., "prefix"++tail)
   (x,x) patterns (hidden ==)

In each case, the question is "what if the Prelude's version
of the explicit or implied function is not in scope?"  (For
n+k patterns, is the relevant function "+" or is it ">=" and "-"?
For l++r patterns, is it "++", or "null", "head", and "tail"?)

My preferred answer would be to say "the only functions in
scope in a pattern are constructors; these aren't functions,
they're syntax, and they always relate to the Prelude."

The Haskell' community's preferred answer seems to be
"avoid the question, ban the lot of them."

It's fair to say that any such pattern _can_ be rewritten to
something Haskell can handle; it's also fair to say that the
result is often less readable, but that a rewrite may reduce
the pain.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with where free variables can be used more than once

2009-07-17 Thread Wolfgang Jeltsch
Am Freitag, 17. Juli 2009 20:38 schrieb Stefan Holdermans:
> Christopher,
>
> > Wouldn't it be great if pattern variables could be used more than once
> > in a pattern? Like so:
> >
> >foo [x,x,_,x] =  "The values are the same!"
> >foo _  = "They're not the same!"
>
> These are called nonlinear patterns. I think Miranda (a precursor of
> Haskell, sort of) used to have them.

Yes, Miranda had them.

I see the following problem with them: Patterns are about the structure of 
data. So using the same variable twice in the same pattern should mean that 
the values that match the variable must have the same structure. This would 
break data abstraction. For example, matching a pair of sets against the 
pattern (x,x) would succeed if both sets were represented by the same tree 
internally, but not succeed if both sets were equal but represented 
differently.

Best wishes,
Wolfgang
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching with where free variables can be used more than once

2009-07-17 Thread Stefan Holdermans

Christopher,


Wouldn't it be great if pattern variables could be used more than once
in a pattern? Like so:

   foo [x,x,_,x] =  "The values are the same!"
   foo _  = "They're not the same!"


These are called nonlinear patterns. I think Miranda (a precursor of  
Haskell, sort of) used to have them.


Cheers,

  Stefan
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching with where free variables can be used more than once

2009-07-17 Thread Christopher Done
Wouldn't it be great if pattern variables could be used more than once
in a pattern? Like so:

foo [x,x,_,x] =  "The values are the same!"
foo _  = "They're not the same!"

where this could be rewritten to:

foo [x,y,_,z] | x == y && x == z = "The values are the same!"
foo _  = "They're not the same!"

It seems like a straight-forward translation and there wouldn't be a
speed hit for normal patterns because it would only be triggered in
compilation where the same free variable appears twice.

Implications are:

1. in ``foo [x,y] = ...'', x has type a
1. in ``foo [x,x] = ...'', x has type Eq a => a

Was this ever considered? Is it a bad idea for some reason I'm not aware of?

On a mildly irrelevant note, I have observed newbies to the language
wonder why on earth it's not already like this.

Cheers
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-16 Thread Sebastian Fischer


On Jul 15, 2009, at 2:30 PM, Hans Aberg wrote:


If ++ could be pattern matched, what should have been the result of
"let (x++y)=[1,2,3] in (x,y)"?

It will branch. In terms of unification, you get a list of  
substitutions.


f :: [a] -> ([a],[a])
f (x ++ y) = (x,y)


For an argument s, any pair (x, y) satisfying s = x ++ y will match.  
That is, if s = [s_1, ..., s_k], the solutions j = 0, ..., k, x =  
[s_1, ..., s_j], y = [s_(j+1), ..., s_k]. And for each one, a  
potentially different value could given. That is, s could produce  
multiple values.


Curry (a Haskell extension with non-determinism) supports exactly that.

Sergio Antoy and Michael Hanus: Declarative Programming with Function  
Patterns
available at: 



--
Underestimating the novelty of the future is a time-honored tradition.
(D.G.)



___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Richard O'Keefe


On Jul 15, 2009, at 9:57 PM, Magicloud Magiclouds wrote:


Hi,
 I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
could not be compiled, parse error.


I apologise to everyone for my previous message in this
thread.  There was a Haskell message in amongst some Erlang
messages, and I thought this was an Erlang problem.

There are some programming languages, including Erlang,
in which  ++  IS accepted as a
.  Haskell is not one of them.  It could be,
and there would be no ambiguity in elementary cases,
and it would no more involve matching against ++ than
n+1 involves matching against +.  Since the pattern on
the left of the ++ is required to be an explicit list,
there is no the slightest question of backtracking or
anything more general than ordinary pattern matching.

Consider
[a,b,c]++xs
 a:b:c:xs

The second is in general shorter (though less clear; it is
a real pity that Haskell syntax doesn't include something
like Clean's [head:tail], the inconsistency is irritating).
It's not the general case that this syntax was invented for,
but the case where the list is a string.

"abc"++xs
'a':'b':'c':xs

One of the arguments advanced against n+k patterns is
"which scope should + be looked up in? what if the + in
the standard prelude is not in scope?"

The same question can be asked about list++tail patterns;
what should it mean if the prelude's ++ was not in scope?

Programmers who have met "abc"++Xs sometimes turn around
and ask for Xs++"abc".  Perhaps it is better to keep the
camel's nose out of the tent.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Richard O'Keefe


On Jul 15, 2009, at 9:59 PM, minh thu wrote:


2009/7/15 Magicloud Magiclouds :

Hi,
I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
could not be compiled, parse error.


++ is a function; you can't pattern-match on that.


Doesn't matter, it's not trying to.
Part of Erlang syntax is that in a pattern
[c1,...,cn] ++ P
is equivalent to
[c1,...,cn|P]

For example,
wee(X) ->
F = fun ([0,1] ++ L) -> L end,
F(X).
is perfectly legal.

The problem might be the "xs", or it might be the "=".
Presumably it should be

fun ([0,1] ++ Xs) -> ...
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Felipe Lessa
On Wed, Jul 15, 2009 at 08:09:37AM -0400, Andrew Wagner wrote:
> Err, technically, aren't functions and constructors mutually exclusive? So
> if something is a function, it's, by definition, not a constructor?

I guess what Eugene Kirpichov meant was that not being a function
(and being a constructor) isn't sufficient, it must also be a
constructor of the correct type, e.g.

  f Nothing = ...
  f (x:xs)  = ...

isn't correct, however it pattern matches on constructors only.

--
Felipe.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Hans Aberg

On 15 Jul 2009, at 13:22, Luke Palmer wrote:


If ++ could be pattern matched, what should have been the result of
"let (x++y)=[1,2,3] in (x,y)"?

It will branch. In terms of unification, you get a list of  
substitutions.


f :: [a] -> ([a],[a])
f (x ++ y) = (x,y)


For an argument s, any pair (x, y) satisfying s = x ++ y will match.  
That is, if s = [s_1, ..., s_k], the solutions j = 0, ..., k, x =  
[s_1, ..., s_j], y = [s_(j+1), ..., s_k]. And for each one, a  
potentially different value could given. That is, s could produce  
multiple values.


If this pattern branches, it could hardly be considered a function  
which takes lists and returns pairs.  It would have to return  
something else.



So this would be a multi-valued function, which sometime is useful as  
a concept. But if the choices are indexed, they can be reduced to a  
single valued function. Like g(x,y) with the requirement that if x ++  
y = x' ++ y', then g(x, y) = g(x', y').


This branching is what would happen if one tries to make a type theory  
based on sets. (It is possible to implement Horn clauses as  
unification branching.) The selection of branches correspond to a  
choice in the proof tree.


  Hans


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Miguel Mitrofanov

No. Most constructors are functions, e.g. Just :: a -> Maybe a - a function.

On the other hand, Nothing :: Maybe a is a constructor, but not a function.

Andrew Wagner wrote:
Err, technically, aren't functions and constructors mutually exclusive? 
So if something is a function, it's, by definition, not a constructor?


On Wed, Jul 15, 2009 at 6:25 AM, Eugene Kirpichov > wrote:


Technically, the reason is not that (++) is a function, but that it is
not a constructor of the [] type.

And, not only is it not a constructor, but it also *can't* be one,
because the main characteristic of pattern matching in Haskell is that
it is (contrary to Prolog's unification) unambiguous (unambiguity of
constructors is guaranteed by the semantics of Haskell's algebraic
datatypes).

If ++ could be pattern matched, what should have been the result of
"let (x++y)=[1,2,3] in (x,y)"?

2009/7/15 minh thu mailto:not...@gmail.com>>:
 > 2009/7/15 Magicloud Magiclouds mailto:magicloud.magiclo...@gmail.com>>:
 >> Hi,
 >>  I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
 >> could not be compiled, parse error.
 >
 > ++ is a function; you can't pattern-match on that.
 >
 > Cheers,
 > Thu
 > ___
 > Haskell-Cafe mailing list
 > Haskell-Cafe@haskell.org 
 > http://www.haskell.org/mailman/listinfo/haskell-cafe
 >



--
Eugene Kirpichov
Web IR developer, market.yandex.ru 
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org 
http://www.haskell.org/mailman/listinfo/haskell-cafe





___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Andrew Wagner
Err, technically, aren't functions and constructors mutually exclusive? So
if something is a function, it's, by definition, not a constructor?

On Wed, Jul 15, 2009 at 6:25 AM, Eugene Kirpichov wrote:

> Technically, the reason is not that (++) is a function, but that it is
> not a constructor of the [] type.
>
> And, not only is it not a constructor, but it also *can't* be one,
> because the main characteristic of pattern matching in Haskell is that
> it is (contrary to Prolog's unification) unambiguous (unambiguity of
> constructors is guaranteed by the semantics of Haskell's algebraic
> datatypes).
>
> If ++ could be pattern matched, what should have been the result of
> "let (x++y)=[1,2,3] in (x,y)"?
>
> 2009/7/15 minh thu :
> > 2009/7/15 Magicloud Magiclouds :
> >> Hi,
> >>  I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
> >> could not be compiled, parse error.
> >
> > ++ is a function; you can't pattern-match on that.
> >
> > Cheers,
> > Thu
> > ___
> > Haskell-Cafe mailing list
> > Haskell-Cafe@haskell.org
> > http://www.haskell.org/mailman/listinfo/haskell-cafe
> >
>
>
>
> --
> Eugene Kirpichov
> Web IR developer, market.yandex.ru
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Luke Palmer
On Wed, Jul 15, 2009 at 3:08 AM, Hans Aberg  wrote:

> On 15 Jul 2009, at 12:25, Eugene Kirpichov wrote:
>
>  If ++ could be pattern matched, what should have been the result of
>> "let (x++y)=[1,2,3] in (x,y)"?
>>
>
> It will branch. In terms of unification, you get a list of substitutions.


f :: [a] -> ([a],[a])
f (x ++ y) = (x,y)

If this pattern branches, it could hardly be considered a *function *which
takes lists and returns pairs.  It would have to return something else.

Luke
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Hans Aberg

On 15 Jul 2009, at 12:25, Eugene Kirpichov wrote:


If ++ could be pattern matched, what should have been the result of
"let (x++y)=[1,2,3] in (x,y)"?


It will branch. In terms of unification, you get a list of  
substitutions.


  Hans


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Eugene Kirpichov
Technically, the reason is not that (++) is a function, but that it is
not a constructor of the [] type.

And, not only is it not a constructor, but it also *can't* be one,
because the main characteristic of pattern matching in Haskell is that
it is (contrary to Prolog's unification) unambiguous (unambiguity of
constructors is guaranteed by the semantics of Haskell's algebraic
datatypes).

If ++ could be pattern matched, what should have been the result of
"let (x++y)=[1,2,3] in (x,y)"?

2009/7/15 minh thu :
> 2009/7/15 Magicloud Magiclouds :
>> Hi,
>>  I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
>> could not be compiled, parse error.
>
> ++ is a function; you can't pattern-match on that.
>
> Cheers,
> Thu
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



-- 
Eugene Kirpichov
Web IR developer, market.yandex.ru
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread minh thu
2009/7/15 minh thu :
> 2009/7/15 Magicloud Magiclouds :
>> Hi,
>>  I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
>> could not be compiled, parse error.
>
> ++ is a function; you can't pattern-match on that.

But here you can match against (0:1:xs).
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread minh thu
2009/7/15 Magicloud Magiclouds :
> Hi,
>  I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
> could not be compiled, parse error.

++ is a function; you can't pattern-match on that.

Cheers,
Thu
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching does not work like this?

2009-07-15 Thread Magicloud Magiclouds
Hi,
  I do not notice this before. "fun ([0, 1] ++ xs) = .." in my code
could not be compiled, parse error.

-- 
竹密岂妨流水过
山高哪阻野云飞
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] pattern matching on date type

2009-01-01 Thread Bulat Ziganshin
Hello Max.cs,

Thursday, January 1, 2009, 11:36:24 AM, you wrote:

seems that you come from dynamic languages :)

Haskell has static typing meaning that your function can accept either
Tree or a as arguments. so you should convert a to Tree explicitly,
using Leaf


>   
>  
> thanks!
>  
>  
>  
> suppose we have 
>  
>  
>  
>> data Tree a = Leaf a | Branch (Tree a) (Tree a)  deriving Show
>  
>  
>  
> and how I could define a function foo :: a -> Tree a that
>  
>  
>  
> foo a = Leaf  a where a is not a type of  Tree
>  
> foo b =  b where  b is one of the type of Tree (Leaf or 
> Branch) ?
>  
>  
>  
> The following code seems not working..
>  
>  
>  
> foo (Leaf a) = a
>  
> foo a = Leaf a
>  
>  
>  
> saying 'Couldn't match expected type `a' against  inferred type `Btree a''
>  
>  
>  
> any idea?
>  
>  
>  
> Thanks,
>  
> Max
>  
>  
>  
>  

>  
>  
> From: Brandon S. Allbery KF8NH 
>  
> Sent: Thursday, January 01, 2009 7:35 AM
>  
> To: Max.cs 
>  
> Cc: Brandon S. Allbery KF8NH ; beginn...@haskell.org ; 
> haskell-cafe@haskell.org
>  
> Subject: Re: [Haskell-cafe] definition of data
>  

>  
>  
> On 2009 Jan 1, at 2:32, Max.cs wrote: 
>  
>   
>   
> data Tree a = a | Branch (Tree a) (Tree a)deriving Show
>   
>  
>   
> but it seems not accpetable in haskell ?
>   


>  
> You need a constructor in both legs of the type:
>  

>  
>> data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show
>  

>  
>  
>  



-- 
Best regards,
 Bulatmailto:bulat.zigans...@gmail.com

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] pattern matching on date type

2009-01-01 Thread Max.cs
thanks!

suppose we have 

> data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show

and how I could define a function foo :: a -> Tree a that

foo a = Leaf a where a is not a type of Tree
foo b = b where b is one of the type of Tree (Leaf or Branch) ?

The following code seems not working..

foo (Leaf a) = a
foo a = Leaf a

saying 'Couldn't match expected type `a' against inferred type `Btree a''

any idea?

Thanks,
Max



From: Brandon S. Allbery KF8NH 
Sent: Thursday, January 01, 2009 7:35 AM
To: Max.cs 
Cc: Brandon S. Allbery KF8NH ; beginn...@haskell.org ; haskell-cafe@haskell.org 
Subject: Re: [Haskell-cafe] definition of data


On 2009 Jan 1, at 2:32, Max.cs wrote: 
  data Tree a = a | Branch (Tree a) (Tree a) deriving Show

  but it seems not accpetable in haskell ?


You need a constructor in both legs of the type:


> data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show


-- 
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allb...@kf8nh.com
system administrator [openafs,heimdal,too many hats] allb...@ece.cmu.edu
electrical and computer engineering, carnegie mellon universityKF8NH


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


RE: [Haskell-cafe] Pattern matching on numbers?

2008-11-19 Thread Tobias Bexelius
Yes, fromInteger and == is used for pattern matching on numbers.
However, on GHC you can use -XNoImplicitPrelude to make it use whatever
fromInteger and == that's in scope (without any Num or Eq).

Eg. if == is a method of MyEq class and fromInteger is a method of
MyNum, and MyNum doesn't inherit MyEq, then the type of this function

f 0 = ""
f x = 'e' : f (x-1)

Will be inferred as (MyEq a, MyNum a) => a -> String

/Tobias

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of David Menendez
Sent: den 19 november 2008 01:00
To: Henning Thielemann
Cc: Haskell Cafe
Subject: Re: [Haskell-cafe] Pattern matching on numbers?

On Tue, Nov 18, 2008 at 6:56 PM, Henning Thielemann
<[EMAIL PROTECTED]> wrote:
>
> On Tue, 18 Nov 2008, Ryan Ingram wrote:
>
>> How does this work?
>>
>>> fac n = case n of
>>>   0 -> 1
>>>   _ -> n * fac (n-1)
>>
>> ghci> :t fac
>> fac :: (Num t) => t -> t
>>
>> The first line of "fac" pattern matches on 0.  So how does this work 
>> over any value of the Num typeclass?  I know that the "1" on the rhs 
>> of fac are replaced with (fromInteger 1), but what about numeric 
>> literals in patterns?  Does it turn into a call to (==)?
>
> As far as I know, yes. It is even possible to trap into an error on 
> pattern matching this way if fromInteger generates an 'undefined'.

As I understand it, the use of (==) in numeric pattern matching is why
Num requires Eq.

--
Dave Menendez <[EMAIL PROTECTED]>
<http://www.eyrie.org/~zednenem/>
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching on numbers?

2008-11-18 Thread David Menendez
On Tue, Nov 18, 2008 at 6:56 PM, Henning Thielemann
<[EMAIL PROTECTED]> wrote:
>
> On Tue, 18 Nov 2008, Ryan Ingram wrote:
>
>> How does this work?
>>
>>> fac n = case n of
>>>   0 -> 1
>>>   _ -> n * fac (n-1)
>>
>> ghci> :t fac
>> fac :: (Num t) => t -> t
>>
>> The first line of "fac" pattern matches on 0.  So how does this work
>> over any value of the Num typeclass?  I know that the "1" on the rhs
>> of fac are replaced with (fromInteger 1), but what about numeric
>> literals in patterns?  Does it turn into a call to (==)?
>
> As far as I know, yes. It is even possible to trap into an error on pattern
> matching this way if fromInteger generates an 'undefined'.

As I understand it, the use of (==) in numeric pattern matching is why
Num requires Eq.

-- 
Dave Menendez <[EMAIL PROTECTED]>

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching on numbers?

2008-11-18 Thread Henning Thielemann


On Tue, 18 Nov 2008, Ryan Ingram wrote:


How does this work?


fac n = case n of
   0 -> 1
   _ -> n * fac (n-1)


ghci> :t fac
fac :: (Num t) => t -> t

The first line of "fac" pattern matches on 0.  So how does this work
over any value of the Num typeclass?  I know that the "1" on the rhs
of fac are replaced with (fromInteger 1), but what about numeric
literals in patterns?  Does it turn into a call to (==)?


As far as I know, yes. It is even possible to trap into an error on 
pattern matching this way if fromInteger generates an 'undefined'.



Should whatever technique is used be extended to other typeclasses too?


 It is unusual to do pattern matching on fractions, you mostly need it for 
recursion on natural numbers. Thus I think the cleanest solution would be 
to treat natural numbers like strict Peano numbers

  data PeanoStrict = Zero | Succ !PeanoStrict
 but with an efficient implementation using GMP integers, maybe using 
'views', if they were part of Haskell language. Then you can implement:


fac :: Integer -> Integer
fac Zero = 1
fac n1@(Succ n) = n1 * fac n

 I would then give up pattern matching on any numeric type.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching on numbers?

2008-11-18 Thread Ryan Ingram
How does this work?

> fac n = case n of
>0 -> 1
>_ -> n * fac (n-1)

ghci> :t fac
fac :: (Num t) => t -> t

The first line of "fac" pattern matches on 0.  So how does this work
over any value of the Num typeclass?  I know that the "1" on the rhs
of fac are replaced with (fromInteger 1), but what about numeric
literals in patterns?  Does it turn into a call to (==)?

Should whatever technique is used be extended to other typeclasses too?

  -- ryan
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching error

2007-12-06 Thread Ketil Malde
"Philip Weaver" <[EMAIL PROTECTED]> writes:

> You'll find that the pattern that it's failing to match is:
>
>[('b',[5,4]),('b',[1]),('b',[6])]

You could also use ghc with -Wall, which will tell you exactly which
cases you've omitted.

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching error

2007-12-06 Thread Philip Weaver
If you add a third pattern, you can see exactly what it's failing to match:

kmerge x = error (show x)

In order to do this, you just need to add Show constraints for a and b in
the type of kmerge:

   kmerge :: (Show a, Show b, Eq a) => [(a,[b])]->[(a,[b])]

You'll find that the pattern that it's failing to match is:

   [('b',[5,4]),('b',[1]),('b',[6])]

Because you combined 5 and 4 and passed that on to your recursive 'kmerge'
call.  Your patterns only cover the case where there is exactly one element
in the list.

- Phil

On Dec 6, 2007 9:39 AM, georg86 <[EMAIL PROTECTED]> wrote:

>
> Hello!
> I need to write a function which should is supposed to merge multiple
> entries with the same
> key (out of a sorted key-value-list) into one single entry.
> However, I keep getting a pattern matching error.
>
> (For example, for input [('b',[5]),('b',[4]),('b',[1]),('b',[6])]:
> "Program error: pattern match failure: kgroup
> [('b',[5,4]),('b',[1]),('b',[6])]")
>
> Thank you very much for your help.
>
> kmerge::Eq a => [(a,[b])]->[(a,[b])]
>
> kmerge [] = []
>
> kmerge ((x,[y]):[]) = [(x,[y])]
>
> kmerge ((x,[y]):(u,[v]):xs) | x == u = kmerge ((x,[y,v]):xs)
> | otherwise = (x,[y]):(u,[v]):kmerge
> xs
> --
> View this message in context:
> http://www.nabble.com/Pattern-matching-error-tf4957268.html#a14196413
> Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
>
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching error

2007-12-06 Thread Brent Yorgey
> kmerge ((x,[y]):[]) = [(x,[y])]
>

Matching on [y] like this will only match lists with a single element (and
bind y to that element).  You probably just want to say

kmerge ((x,y):[]) = [(x,y)]

etc., which will bind y to the entire list.

-Brent
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching error

2007-12-06 Thread georg86

Hello!
I need to write a function which should is supposed to merge multiple
entries with the same
key (out of a sorted key-value-list) into one single entry.
However, I keep getting a pattern matching error.

(For example, for input [('b',[5]),('b',[4]),('b',[1]),('b',[6])]: 
"Program error: pattern match failure: kgroup
[('b',[5,4]),('b',[1]),('b',[6])]") 

Thank you very much for your help.

kmerge::Eq a => [(a,[b])]->[(a,[b])]

kmerge [] = []

kmerge ((x,[y]):[]) = [(x,[y])]

kmerge ((x,[y]):(u,[v]):xs) | x == u = kmerge ((x,[y,v]):xs) 
 | otherwise = (x,[y]):(u,[v]):kmerge xs
-- 
View this message in context: 
http://www.nabble.com/Pattern-matching-error-tf4957268.html#a14196413
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching articles/explanations

2007-08-16 Thread Neil Mitchell
Hi

> So what I noticed that "A Gentle Introduction to Haskell" mentioned
> that wild-cards are useful in constructors. For example:
>
> head (x:_) = x
>
> So, does that offer any performance benefits over:
>
> head (x:xs) = x

No. They are exactly the same. _ simply means "a new unique name".

> Or is it primarily to indicate to the coder that xs is useless?

Yes

> I get
> the impression it has a very similar meaning to the irrefutable
> pattern in regards to not evaluating it when the function is called.
> Or am I way off?

Way off :-) Nothing to do with irrefutable patterns, or demand of
evaluation, its got two uses:

1) Indicate to the reader that this argument is never used
2) Save you coming up with a name for the argument

Thanks

Neil
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching articles/explanations

2007-08-16 Thread Ian Duncan
So what I noticed that "A Gentle Introduction to Haskell" mentioned  
that wild-cards are useful in constructors. For example:


head (x:_) = x

So, does that offer any performance benefits over:

head (x:xs) = x

Or is it primarily to indicate to the coder that xs is useless? I get  
the impression it has a very similar meaning to the irrefutable  
pattern in regards to not evaluating it when the function is called.  
Or am I way off?

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching articles/explanations

2007-08-15 Thread Ian Duncan
Hello everyone, I've been working on improving my Haskell knowledge,  
and in doing so, I have read a little about as-patterns as well as  
some form of pattern that uses "~" that I don't really understand. I  
suspect there are even more lesser-known pattern matching expressions  
than just these, but I don't have the stamina to decode the Haskell  
98 Report. Are there any articles anyone is aware of, or anything in  
the Haskell wiki that covers the built-in pattern matching facilities  
pretty comprehensively? I've looked in the Haskell wiki myself, but  
information on different pattern matching abilities seems rather  
scattered and I'm not entirely sure what I should be looking for.


Thanks,
Ian Duncan
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching

2007-01-15 Thread Stefan Aeschbacher

2007/1/15, Stefan O'Rear <[EMAIL PROTECTED]>:

On Mon, Jan 15, 2007 at 10:09:10AM +0100, Stefan Aeschbacher wrote:
> Hi
>
> I sometimes have a function definition similar to this:
>
> myFunction x@(Constructor1 _ _ _ _ _ _) = ...
> myFunction x@(Constructor2 _ _ _ _ _ _ _ _) = ...

myFunction [EMAIL PROTECTED] = ...
myFunction [EMAIL PROTECTED] = ...

this works even for non-record types


I didnt know about the possibilty to use {}. This solves my problem
quite nicely.

thanks
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching

2007-01-15 Thread Neil Mitchell

Hi Stefan,



myFunction x@(Constructor1 _*) = ...
myFunction x@(Constructor2 _*) = ...


myFunction x@(Constructor1 {}) =
myFunction x@(Constructor2 {}) =



myFunction2 (Constructor1 _* a _*) = ...

could be possible as long as the pattern is non-ambiguous (in this
case, only one variable with the type of a is present in this
constructor).


In this context a is not a type, but a value, and the non-ambiguous
constraint can get pretty confusing in a case like this. The answer is
to use records:

data Data = Constructor1 {field1 :: Bool, field2 :: Int, field3 :: Int}

myFunction (Constructor1 {field2=a}) = ...

Thanks

Neil
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Pattern matching

2007-01-15 Thread Stefan O'Rear
On Mon, Jan 15, 2007 at 10:09:10AM +0100, Stefan Aeschbacher wrote:
> Hi
> 
> I sometimes have a function definition similar to this:
> 
> myFunction x@(Constructor1 _ _ _ _ _ _) = ...
> myFunction x@(Constructor2 _ _ _ _ _ _ _ _) = ...

myFunction [EMAIL PROTECTED] = ...
myFunction [EMAIL PROTECTED] = ...

this works even for non-record types
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching

2007-01-15 Thread Stefan Aeschbacher

Hi

I sometimes have a function definition similar to this:

myFunction x@(Constructor1 _ _ _ _ _ _) = ...
myFunction x@(Constructor2 _ _ _ _ _ _ _ _) = ...

which in my eyes is not very elegant and easy to type. Is there an easier way to
switch on the different constructors of a type (Data.Generics
certainly could be used..)?

If not, has thought been put in a pattern matching possibility of the
form _*. This
would allow:

myFunction x@(Constructor1 _*) = ...
myFunction x@(Constructor2 _*) = ...

Also pattern matches of the form:

myFunction2 (Constructor1 _* a _*) = ...

could be possible as long as the pattern is non-ambiguous (in this
case, only one variable with the type of a is present in this
constructor).

regards

Stefan
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Pattern matching problems

2005-09-23 Thread Marcin Tustin
In case I confused anyone, this is a separate issue. Thanks for your 
attention and help.

On Sat, Sep 24, 2005 at 01:20:22AM +0100, Marcin Tustin wrote:
> 
> For some reason the following code is producing an error message from ghci 
> that the the patterns are non-exhaustive. Does anyone have any idea why that 
> could be, given that the patterns are, at least in my meaning, provably 
> exhaustive?
> 
> choosenonuniqueset n (a:r)
> | (length r) >  (n-1) = [ (sort (a:x)) | x <- (choosenonuniqueset (n-1) 
> r)] 
> `union`
> [ (sort (a:x)) | x <- (choosenonuniqueset n r)]
> | (length r) == (n-1) = [a:r]
> | (length r) <  (n-1) = []
> 
> Error message is:
> 
> *Main> :reload
> Compiling Main ( birthday.hs, interpreted )
> Ok, modules loaded: Main.
> *Main> choosenonuniqueset 2 [1..5]
> *** Exception: birthday.hs:(22,0)-(27,29): Non-exhaustive patterns in 
> function choosenonuniqueset
> 
> *Main> choosenonuniqueset 5 [1..5]
> [[1,2,3,4,5]]
> *Main>
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe