0

Implement a search algorithm that searches through a list for Int n and returns the value in the list before n. If there is no value, or the list is empty, return -1. e.g., findPrev 5 [1,2,3,4,5,6] should return 4, while findPrev 5 [0, 10, 20, 30] returns -1.

I got this for the find the number, but have no idea how to get the previous number. Can someone help and explain this one to me? Here is how I did the first one:

findNext :: Int -> [Int] -> Int
findNext _ [] = -1
findNext n (x:xs)
    | n == x = head xs
    | otherwise = findNext n xs
1

4 Answers 4

4

You can use pattern matching to get the previous value. Just define your pattern for the matching case as x:y:xs to match a list with at least two elements. The cases for empty and singleton lists can be spelled out explicitly in other cases:

findPrev :: Int -> [Int] -> Int
findPrev _ [] = -1
findPrev _ [_] = -1
findPrev n (x:y:xs) = if n == y then x else findPrev n (y:xs)
Sign up to request clarification or add additional context in comments.

Comments

1

Outside-the-box (but inefficient) answer: use findNext on the reversal of the list.

findPrev x xs = findNext x (reverse xs)

Comments

0
findPrev :: Int -> [Int] -> Int
findPrev _ [] = -1
findPrev n (x:xs)
    | xs == [] = -1
    | n == head xs = x
    | otherwise = findPrev n xs

2 Comments

Yeah, that is my code for the first problem that I had. What I posted was that I need to do it for the previous number in the list now, which is where I get lost. I even posted that same code up top so everyone can see what I have so far in terms of doing it for the next number because that one I understand
Sorry, @loutej. I forgot to change the function's name. It might make you confused, however this code works exactly like what you want...
0

Assuming the list is ordered:

module FindPrevious where

findPrevious n xs 
    | n `elem` xs = last $ takeWhile (<n) xs
    | otherwise = (-1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.