我正在尝试实施fixed point
功能,如下所示
fixedPoint :: (Fractional a,Ord a ) => (a -> a ) -> a -> a
fixedPoint f initialGuess= let x= f initialGuess
in if (closeEnough initialGuess x)
then x
else fixedPoint f x
这个函数在调用fixedPoint cos 1
并返回0.7390851699445544
时效果很好但是,我想记录函数完成的步骤并使用writer monad将其添加到字符串中,调整后的函数是按照以下
fixedPoint' :: (Fractional a,Ord a,Show a) => (a -> a ) -> a -> Writer [String] a
fixedPoint' f initialGuess=
let x = f initialGuess
in
if (closeEnough initialGuess x ) then
do
tell ["Ending with" ++ show initialGuess]
return x
else
do
result <- fixedPoint' f x
tell ["Trying Guess" ++ show initialGuess]
return result
调用函数mapM_ putStrLn $ snd $ runWriter (fixedPoint' cos 1)
时返回空元组