[Haskell-beginners] why is something different within a function
when it comes out?
Chaddaï Fouché
chaddai.fouche at gmail.com
Wed Jul 14 04:54:22 EDT 2010
On Wed, Jul 14, 2010 at 7:33 AM, prad <prad at towardsfreedom.com> wrote:
> xtract p c = do
> let r = c=~p::[[String]]
> return r!!0!!0!!1
return is just a function in Haskell, and given that function
application has priority over any operator, this mean your last line
is :
> (return r) !! 0 !! 0 !! 1
return type is "(Monad m) => a -> m a" where m is a type constructor
variable (a type constructor is a parametrized type, think array
parametrized on the element type in most language, or template in C++)
constrained to be an instance of the Monad typeclass. Monad is an
important typeclass in Haskell but here it's enough to look at (!!)
type "[a] -> Int -> a" to see that (return r) should be of a list
type, list is a monad so this code typecheck, but return is perfectly
redundant :
For the list monad :
> return x = [x]
so in this case your last line put r in a singleton list :
> [r] !! 0 !! 0 !! 1
then (!! 0) extract r
> r !! 0 !! 1
And you get what you wanted in the first place...
So you could write just "r !! 0 !! 1" instead of "return r!!0!!!0!!1"
for the same result.
In fact xtract could be written :
> xtract p c = (c =~ p :: [[String]]) !! 0 !! 1
do-notation (which is just syntactic sugar to write monadic code
easily) and return (which is just a function, not a keyword) are only
useful when you're working with monads, if you're not you shouldn't
use them.
--
Jedaï
More information about the Beginners
mailing list