0

I know I should be forgetting about iterating in functional languages, but I dont know how else to put forth my question.

If I have a list of integers arranged in ascending or descending order, and I have an arbitrary number that may or may not be present in the list, how can I loop over the list to find a number that is small than the given number and return that integer.

I just need to know how to go about it.

11
  • Does the elem function work for you? Commented Nov 28, 2014 at 17:03
  • You recurse, as usual. Commented Nov 28, 2014 at 17:03
  • 1
    @user5402 No, elem doesn't do what OP asked for. Commented Nov 28, 2014 at 17:04
  • 1
    Show some of your attempts. Commented Nov 28, 2014 at 17:14
  • 1
    to return the largest number in the list not greater than the input number, last . takeWhile (<= input) $ xs. To accommodate your latest requirement, let (a,b)=span(<= input) xs in head $ [input|null b]++[last a]. Commented Nov 28, 2014 at 20:20

3 Answers 3

2

You could use find to find the first element matching a predicate you specify. Example:

find even [3,5,7,6,2,3,4]

Or, you could drop all the unwanted elements from the left:

dropWhile (not . even) [3,5,7,6,2,3,4]

(and possibly take the first element remaining, which has to be even).

Or, you could filter out unwanted elements

filter even [3,5,7,6,2,3,4]

Or, you could use recursion and code everything yourself.

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

Comments

0

You can recursively deconstruct the list with pattern matching:

searchList :: Int -> [Int] -> ???
searchList n [] = ??? 
searchList n (x:xs) = ???

You check whether x is the number you want, and if not you can call searchList n xs to search the rest of the list.

The normal way to do something like that would be with the library function foldr, but it would be better to understand how to do this with recursion first.

1 Comment

I think it would be useful to point out that you can also match more than one element and that you can use guards searchList n (x:y:xs) | <condition with x y and n>
0

You can have "state" in a list iteration by using a fold - the state is passed from one iteration to the next in a function argument.

An example:

sup :: [Int] -> Int -> Int
sup xs y = go (head xs) xs
  where
    go s [] = s
    go s (x:xs) = if x >= y then s else go x xs

Here s is the "state" -- it is the latest value in the list that is less than y.

Because you said the input list would never be empty, head xs is okay here.

This is almost what you want. Perhaps you can modify it to handle all of your conditions.

Comments

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.