Convert from arrow notation

半城伤御伤魂 提交于 2019-12-04 06:11:50
{- |
                     +---------+
 >Bool>-------------->         |
                     |         >------------------>Int>
       +---------+   |  arr f  |
  /----> delay 0 >--->         >---------\
  |    +---------+   |         |         |
  |                  +---------+         |
  |                                      |
  \--------------------------------------/ 

 -}
counter' :: ArrowCircuit a => a Bool Int
counter' = loop $ second (delay 0) >>> arr f
  where
    f (reset, next) = let output = if reset then 0 else next
                          next' = output + 1
                       in (output, next')

The recursive rec part is implemented using loop. The inner part that converts reset to output using next (and producing new next value) is just a pure function with two inputs and two outputs.

A parallellism in functional code, would be to use a state op. in a fold

import Data.List

counter :: (Int, Int) -> Bool -> (Int, Int)
counter (_, previous_next) reset  =
   let output = if reset then 0 else previous_next
       next = output +1
   in (output, next)

runCounter :: [Bool] -> (Int, Int) 
runCounter = foldl' counter (0,1)

main = do
   let resets = [True, False, True, False, False]   
       result = fst $ runCounter resets
   print result 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!