在下面的程序中,我只希望cycle3
使用常量內存運行(它明確地連接了結)。但是,由於我無法理解的原因,cycle2
也在恆定內存中運行。我希望cycle2
到做同樣的工作,爲cycle1
因爲周期函數的意外內存使用
xs' = xs ++ xs'
xs' = xs ++ xs ++ xs' -- substitute value of xs'
xs' = xs ++ xs ++ xs ++ xs' -- substitute value of xs' again
xs' = xs ++ xs ++ xs ++ ... -- and so on
有人能解釋什麼,我在這裏失蹤?
module Main where
import System.Environment (getArgs)
cycle1 :: [a] -> [a]
cycle1 [] = error "empty list"
cycle1 xs = xs ++ cycle1 xs
cycle2 :: [a] -> [a]
cycle2 [] = error "empty list"
cycle2 xs = xs' where xs' = xs ++ xs'
cycle3 :: [a] -> [a]
cycle3 [] = error "empty list"
cycle3 xs = let
xs' = go xs' xs
in xs'
where
go :: [a] -> [a] -> [a]
go start [last] = last : start
go start (x:xs) = x : go start xs
testMem :: (Show a) => ([a] -> [a]) -> [a] -> IO()
testMem f xs = print (xs', xs') -- prints only first val, need second val holds onto reference
where
xs' = f xs
main :: IO()
main = do
args <- getArgs
let mCycleFunc = case args of
["1"] -> Just cycle1
["2"] -> Just cycle2
["3"] -> Just cycle3
_ -> Nothing
case mCycleFunc of
Just cycleFunc -> testMem cycleFunc [0..8]
Nothing -> putStrLn "Valid args are one of {1, 2, 3}."