seedkey
seedkey

Reputation: 15

Making a new list inside a function and adding an element into it

I am trying to create a function, that takes a co-ordinate, and then given a set of co-ordinates, it extracts all the coordinates that are within one unit of the given co-ordinates, and then makes a list out of that. I already know how to make this function, I just need clarification as to how I make it RETURN the new list.

For example if I give the function (2,1) [(1,3),(1,2),(3,0),(4,2),(2,2),(3,1)], it would return a list [(1,2),(3,0),(2,2),(3,1)].

I already know how to implement a function that can find if a list is within one unit, I just need to know how take the functions I found matching my pattern, and returning it into a fresh list

local_elements :: Coordinate -> List_with_coordinates -> List_with_coordinates
local_elements (x_c,y_c) list = case list of
  (x_l,y_l) :xs
    | abs (x_l - x_c) <= 1 && abs (y_l - y_c) <=1 -> "what would go here?" local_elements xs
    | otherwise -> local_elements xs        
  [] -> []

Upvotes: 0

Views: 737

Answers (1)

bitmask
bitmask

Reputation: 34644

You make a function

dist :: Int -> Coordinate -> Coordinate -> Bool
dist k (x_c,y_c) (x_1,y_1) = ((abs (x_1 - x_c)) <= k) && ((abs (y_1 - y_c)) <= k)

It checks if a coordinate is fine. Theny ou say:

local_lements c = filter (dist 1 c)

This is sufficient to do exactly what you want. If two coordinates are only 1 apart, dist 1 will return True, and the builtin function filter will take all elements x from list that cause dist 1 c x to return True.

Upvotes: 4

Related Questions