haskellreversefoldablerepresentable

How to write reverseT without using List?


I need an alternative to reverseT that doesn't use toList. Obviously, this code is incorrect, but demonstrates the idea I was pursuing:

reverseF
  :: (Foldable f, Representable f, Num (Rep f))
  => f a -> f a
reverseF f = tabulate $ \ix -> index f $ last - ix
  where last = length f - 1  -- Incorrect; length -> ?

Does anyone know what I can replace length with, so as to get the last index element offered by tabulate when building an f?


Solution

  • You could assume and use Bounded (Rep f) and Enum (Rep f), i.e., convert Rep f to Int with toEnum, change indices by some Int arithmetic that uses Int counterparts of minBound and maxBound on Rep f (or assume fromEnum minBound == 0), and finally from Int back to Rep f with fromEnum.