No puedo dormir! :)Lazy vs Eager evaluación y la construcción de listas de doble enlace
He escrito un programa pequeño que construye una lista de enlaces dobles en Haskell. La propiedad del lenguaje básico para hacerla fue la evaluación perezosa (vea el grupo de código a continuación). Y mi pregunta es ¿puedo hacer lo mismo en un puro lenguaje funcional con evaluación ansioso o no? En cualquier caso, ¿qué propiedades ansioso lenguaje funcional deben tener para poder construir dicha estructura (impureza?)?
import Data.List
data DLList a = DLNull |
DLNode { prev :: DLList a
, x :: a
, next :: DLList a
}
deriving (Show)
walkDLList :: (DLList a -> DLList a) -> DLList a -> [a]
walkDLList _ DLNull = []
walkDLList f [email protected](DLNode _ x _) = x : walkDLList f (f n)
-- Returns first and last items.
makeDLList :: [a] -> (DLList a, DLList a)
makeDLList xs = let (first, last) = step DLNull xs in (first, last)
where
step prev [] = (DLNull, prev)
-- Here I use laziness. 'next' is not built yet, it's a thunk.
step prev (x : xs) = let this = DLNode prev x next
(next, last) = step this xs
in (this, last)
testList :: [Int] -> IO()
testList l = let
(first, last) = makeDLList l
byNext = walkDLList next first
byPrev = walkDLList prev last
in do
putStrLn $ "Testing: " ++ show l
print byNext
print byPrev
main = do
testList []
testList [1, 2, 3, 4]
echa un vistazo a [* this * code] (http://rosettacode.org/wiki/Doubly-Linked_List_%28traversal%29#Haskell). :) Devuelve solo el nodo principal, y es excepcionalmente simple. –