Is there an indexed list in Haskell, and is it good or bad?

I am a new fan of the Haskell world, and I am wondering if there is something like this:

data IndexedList a = IList Int [a]

findIndex::(Int->Int)->IndexedList a->(a,IndexedList a)
findIndex f (IList x l) = (l!!(f x), IList (f x) l)

next::IndexedList a->(a,IndexedList a)
next x = findIndex (+1) x

I noticed that this list is not purely functional, but useful for some applications. Should this be considered harmful?

Thanks,

Bean

+4
source share
2 answers

Of course, it is useful to have a list that has a pointer to a specific place in the list. However, the method that usually runs in Haskell is slightly different - instead of using an explicit pointer, we tend to use a zipper.

The list of lightning looks like this:

data ListZipper a = LZ [a] a [a] deriving (Show)

, a , , [a] , [a] .

, , [0, 1, 2, *3*, 4, 5, 6]

LZ [2,1,0] 3 [4,5,6]

,

left  (LZ (a:as) b bs) = LZ as a (b:bs)
right (LZ as a (b:bs)) = LZ (a:as) b bs

n , , , n

times n f = (!!n) . iterate f

,

>> let lz = LZ [2,1,0] 3 [4,5,6]
>> (3 `times` left) lz
LZ [] 0 [1,2,3,4,5,6]

findIndex next

next :: ListZipper a -> (a, ListZipper a)
next = findIndex 1

findIndex :: Int -> ListZipper a -> (a, ListZipper a)
findIndex n x = let y@(LZ _ a _) = (n `times` right) x in (a, y)
+10

, , . , IList (f x) l (, , IndexedList). , Haskell, unsafePerformIO.

IndexedList, , . l!!(f x) , Haskell . , Maybe a :

findIndex :: (Int -> Int) -> IndexedList a -> (Maybe a, IndexedList a)
findIndex f (IList i l) = (maybe_x, IList new_i l)
    where
        new_i   = f i
        maybe_x = if new_i < length l 
                  then Just (l !! newI) 
                  else Nothing

, , , ;)

+4
source

All Articles