简体   繁体   中英

How do I perform function on tuples within a list comprehension? Haskell

I have a type called image which holds a set of tuples, which are coordinates. I am trying to make a list comprehension where I can print out max and min of the list of either the x or y coordinates.

example :: Image -> (Int,Int)
example e = [ (j,k) | (x,y) <- e, j <- (maximum x), k <- (minimum y)] 

I want to print (max x, min x) as a starter.

I keep getting an error, could someone please show me the correct way of doing this.

edit: Thanks to the answer, I have changed the second line to:

example e = [ (j,k) | (x,y) <- e, let j = maximum x, let k = minimum y]

however get this error:

Couldn't match expected type ‘[a]’ with actual type ‘Int’
Relevant bindings include j :: a (bound at image.hs:69:39)
In the first argument of ‘maximum’, namely ‘x’
In the expression: maximum x

for both j and k

Updated answer:

Here are the definitions of Image and Point :

type Image = [Point]
type Point = (Int,Int)

And how example should be written:

example :: Image -> (Int,Int)
example e = (maximum xs, minimum xs)
  where xs = map fst e   -- xs = list of the x coordinates
        ys = map snd e   -- ys = list of the y coordinates

Original answer:

Use let :

example e = [ (j,k) | (x,y) <- e, let j = maximum x, let k = minimum y]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM