Jump to content

Specific Haskell recursion question

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
cordedconch

cordedconch

    Newbie

  • Members
  • Pip
  • 3 posts
I'm trying to get a haskell program to work.

Basically my program performs basic operations.

I'm trying to write the Grey Scale function.

It would be awesome if someone could help steer me on the right track with these recursion functions.

Edited by cordedconch, 22 March 2010 - 09:04 PM.


#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
I'd use a let expression in greyPixel:
greyPixel :: Pixel -> Pixel[FONT=monospace]
[/FONT]greyPixel (r,g,b) = let a = (r+g+b) `div` 3 in (a, a, a)
A where expression would also work.

I think your problem (if it's a build problem, that is) is in the greyscale function:
greyscale :: Transform
greyscale  []         = [][SIZE=4]
[/SIZE]grayscale  (row:rows) =  greyPixel greyRow row : greyPixel rows
This code:
greyPixel greyRow row
does NOT run greyRow on row then pass the results to greyPixel, this runs greyPixel with two parameters, greyRow and row. This is obviously not what you want, further it won't even work even if you scoped it properly. You should eliminate "greyPixel" from that, also you're inconsistent with your spelling of 'grey', which in this function is spelled both 'grey' and 'gray'. It should look like this:
greyscale  (row:rows) = greyRow row : greyscale rows
Also your greyRow function isn't recursing properly, again to perform recursion you're supposed to define the function in terms of itself. Like this for greyRow:
greyRow []             = []
greyRow (pixel:pixels) = greyPixel pixel : [B]greyRow[/B] pixels
However, in all these cases I wouldn't even bother using recursion. It's considered idiomatic in the Haskell community to not use direct recursion whenever possible, so unless your assignment directly mandates it I'd just use the map expression.
greyscale :: Transform
greyscale = map (map (\(r,g,b) -> let a = (r+g+b) `div` 3 in (a,a,a)))
Done.

Edited by ZekeDragon, 20 March 2010 - 11:35 AM.

Wow I changed my sig!

#3
ziwei

ziwei

    Newbie

  • Members
  • Pip
  • 1 posts
Hi, I wrote the greyscale program and it doesn't work, so I tried and figure out what's wrong. I am so luck to find your reply. However, after I compare what my modules and yours, I found they are exactly the same. But it just doesn't work!!I really got despaired. Could you help to find out what's wrong with my program?

#4
mings

mings

    Newbie

  • Members
  • Pip
  • 2 posts
thank you for your forum.It's helpful for me.