[Haskell-cafe] [Haskell-beginners] boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]

Jack Henahan jhenahan at uvm.edu
Tue Jun 21 22:22:19 CEST 2011


Hi Anthony.

What you've got there is a list comprehension. I'll try to break down what it says for you.

The basic structure of a list comprehension is

function <arguments> = [ description of the list ]

In this function, the argument 'xs' is a Haskell idiom. We use 'xs' to mean "a list of x's". 'xs' doesn't *have* to be a list (since you can call anything 'xs'), but conventionally it is. So 'boomBang xs' simply means "the function boomBangs takes a list xs as an argument."

Now the odd part, the list comprehension itself.

The first part describes what will be in the list, and the second part limits it. What this comprehension does is construct a list of all the odd members of the list 'xs' (in this case, they're numbers) and map "BOOM!" to values under 10, and "BANG!" to anything above 10. So what is says is "if the nth number in my list is less than 10, I want you to make the nth element of the new list "BOOM!", otherwise I want you to make it "BANG!". Furthermore, I only want you to consider odd values of x from my list."

So

testList xs = [ x | x <- xs, odd x ]

called with the list [1,4,8,9,12,15] would return

[1,9,15] -- That is, all the odd members of the list xs

Now, if 'x' is the expression 'if x < 10 then "BOOM!" else "BANG!"', the list returned is instead

["BOOM!","BOOM!","BANG!"]

Decent explanation? Or have I just muddled the issue?

On Jun 21, 2011, at 3:58 PM, anthony niro wrote:

> Hello,
> 
> My name is Anthony i have few question about Haskell.
> 
> I was reading a tutorial everything goes well. but now i have few things that i dont understang.
> 
> HERE:
> 
> boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
> 
> 
> 
> I dont understand this line except the "if" "then" "else".  
> What is xs? 
> what is the |  ? 
>  and why doing this  "  | x <- xs, odd x]"
> 
> why x <- xs????? what is that 
> 
> and what is odd x? 
> 
> thx everyone for answer me. 
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

-------------- next part --------------
A non-text attachment was scrubbed...
Name: 398E692F.asc
Type: application/x-apple-msg-attachment
Size: 24295 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110621/f15dff7d/attachment.bin>
-------------- next part --------------


-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 881 bytes
Desc: This is a digitally signed message part
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110621/f15dff7d/attachment.pgp>


More information about the Haskell-Cafe mailing list