0

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        
  [] -> []
1
  • 1
    Although it's a bit nitpicking, in functional program one in general does not add elements to lists. Once a variable gets a value. It normally cannot change that value anymore... Functional programming makes use of persistent datastructures. Commented Apr 2, 2015 at 12:24

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, thanks for that :) I knew filter had something to do with it. So the filter function will return a new list with all the matched elements in it?
@seedkey: Well, not exactly. The expression filter (dist 1 c) returns a function that has the following property: It takes a list of coordinates and returns a list of coordinates. The returned list will only contain those coordinates with a distance at most 1 from c. You may type :t filter and :t filter (dist 1 c) into your ghci/hugs prompt to see what type they have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.