Haskell: Minimum Position

I start in Haskell terms. I have to do an exercise showing all the minimum positions. For example: [1,2,3,1,1] => 0,3,4 these are the minimum positions. I tried to do this in two ways, but it will not work. Please can anyone help me with a recursive version?

Firstly:

findPos :: [Int]->Int->[Int]
findPos list minimum (list) = [index | (index, e) <- zip [0..] list, e == minimum (list)]

Secondly:

findPos :: [Int]->Int->[Int]
findPos list (minim el) = [index | (index, e) <- zip [0..] list, e == (minim el)]


minim :: [Int] -> Int
minim x = if (tail(x)==[]) then head(x)
      else n 
      where n = minim (tail(x))
            n = if n < head(x) then n
            else head(x)
+4
source share
3 answers

Problem with your code

findPos :: [Int] -> Int-> [Int]
findPos list minimum (list) = ...

This is simply wrong. You will find the minimum later (s minimum list); no need to pass it:

findPos :: [Int] -> [Int]
findPos list = ...

My decision

Not recursive, but how do I personally do it.

I like the solutions for zipping a lot, and I'm not sure why you chose understanding.

  • Find the smallest item.
  • Record your data with [0..].
  • , snd, .
  • fst .

Live on Coliru


xs = [1,2,3,1,1]

findPos = map fst . filter (\e -> snd e == x) . zip [0..]
    where
        x = minimum xs

main = print $ findPos xs
+2

, - .

:

findPos :: [Int] -> Int-> [Int]
findPos list minimum (list) = …

? , findPos, , . :

findPos list m = [index | (index, e) <- zip [0..] list, e == m]

minim , minim findPos, , :

findPos' :: [Int] -> [Int]
findPos' list = findPos list (minim list)

:

findPos :: [Int] -> [Int]
findPos list = [index | (index, e) <- zip [0..] list, e == minim list]

minim , findPos .


. :

minim :: [Int] -> Int
minim (x : []) = x
minim (x : xs) = if x < m then x else m
  where
    m = minim xs

minim , , n.

+2

, , . , , foldr.

-- | Accumulate function
--
acc :: Ord a => (t, a) -> ([t], a) -> ([t], a)
acc (i, x) z@(is, y) = case compare x y of
  LT -> ([i], x)   -- a new minimum! reinit the list of mins
  EQ -> (i:is, y)  -- equal minimum; add to the list of mins
  _  -> z          -- larger than min; accumulator unchanged

findPos = (Bounded a, Ord a) => [a] -> [Int]
findPos = fst . foldr acc ([], maxBound) . zip [(0 :: Int)..]

, zip ( ) , ([], maxBound) ( ), .

Bounded ( findPos Integer ), Maybe, .

Keeping track of the "minimum visible value", as well as the indices where this value was visible, allows you to build a stream processing machine that you could ask at any time, "what were the minimum values ​​in the (possibly infinite) input stream so far.

+1
source

All Articles