[Haskell-beginners] Pattern Matching & Binding
Emmanuel Surleau
emmanuel.surleau at gmail.com
Thu May 8 06:13:23 UTC 2014
On Tue, May 06, 2014 at 02:29:26PM -0400, Ari King wrote:
> >
> > I don't have pg installed so I can't run your code but I assume you are
> > breaking on the vector pattern matching. Pattern matching using : only
> > works because the : operator is a constructor in lists.
> >
> > >:i (:)
> > data [] a = ... | a : [a]
> >
> > Remember that : is an infix operator, but it is comparable to Just, Left,
> > or Right. You are trying to use a list constructor to pattern match on a
> > vector which looks nothing like a list.
> >
> > However you can do this sort of pattern matching by using vector's (or
> > almost any other collection's) toList function:
> >
> > hostaddr:port:dbname:username:password:rest = toList vec
> >
> >
> Thanks for the clarification; I was under the impression that vectors were
> essentially re-implemented lists.
>
>
> > <- is a monadic binding. You use it when you are dealing with a datatype
> > that happens to be an instance of Monad. It happens to be the only way to
> > get anything out of an IO type, which is what you are using it for here.
> > If something is just
> >
> using plain types, Int, String, etc, just use lets.
> >
> >
> So, <- is more like extract (from IO type) and bind, but scoping wise is
> the same as let or where, correct?
It's more complicated than that. Haskell uses monads for IO, this is true, but
it is used in many other places. The first example of monads you're likely to
find is actually Maybe. For instance:
example :: String -> Maybe String
example = do
-- if someFunctionReturningMaybeInt returns (Just anInt),
-- binds 'anInt' to a, otherwise if None just exit the function and return
-- None
a <- someFunctionReturningMaybeInt
b <- someFunctionTakingIntAndReturningMaybeString a
-- if someFunctionTakingIntAndReturningMaybeString returns (Just str),
-- binds 'str' to b, otherwise if None just exit the function and return
-- None
Just $ b ++ "_example"
-- equivalent to: return $ b ++ "_example"
This brings me to the second point: monads are used for sequencing. Here, 'b' is
not available in the first line of the function, it hasn't been bound yet. On
the other hand, the 'let x = foo in'/'where x = foo' syntax makes the name
available in the scope of the function.
> Lastly, the code fails to read (see line 16 @ http://pastebin.com/R5MPNaHs)
> the provided file into a ByteString, ByteString readFile complains:
>
> Failed reading: conversion error: expected Char, got "127.0.0.1"
>
> The file contents are: 127.0.0.1,5432,sample,test_user,test_pwd
>
> Am I misusing, ByteString's readFile? Thanks.
>
> -Ari
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
More information about the Beginners
mailing list