Advertisement
Yevano

Untitled

Nov 8th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.Word
  2. import Control.Monad.ST
  3.  
  4. data Machine = Mn { tape :: [Word8]
  5.                   , ptr :: Word16
  6.                   }
  7.  
  8. data Mode = Inc | Dec
  9.  
  10. newMachine = Mn (take 30000 (repeat 0)) 0
  11.  
  12. modify :: Mode -> Machine -> Machine
  13. modify mode m = do { let p = splitAt (fromIntegral $ ptr m) $ tape m
  14.                    ; let s = snd p
  15.                    ; let n = (case mode of Inc -> \x -> x + 1
  16.                                            Dec -> \x -> x - 1) (head s)
  17.                    ; Mn ((fst p) ++ n : (tail s)) $ ptr m
  18.                    }
  19.  
  20. sel :: Mode -> Machine -> Machine
  21. sel mode m = Mn (tape m) $ (case mode of Inc -> (+1)
  22.                                          Dec -> flip (-) 1) (ptr m)
  23.  
  24. loop :: (Machine -> Machine) -> Machine -> Machine
  25. loop f m = do { let mem = (tape m) !! (fromIntegral $ ptr m)
  26.               ; case mem == 0 of True  -> m
  27.                                  False -> loop f (f m)
  28.               }
  29.  
  30. applyN :: (Num n, Ord n) => n -> (a -> a) -> a -> a
  31. applyN 1 f x = f x
  32. applyN n f x = f (applyN (n-1) f x)
  33.  
  34. seli m = sel    Inc m
  35. seld m = sel    Dec m
  36. modi m = modify Inc m
  37. modd m = modify Dec m
  38.  
  39. -- +++++[>+++++<-]
  40. main = print $ take 10 $ tape $ ( (loop $ modd
  41.                                         . seld
  42.                                         . applyN 1000 modi
  43.                                         . seli)
  44.                                 . applyN 1000 modi) newMachine
  45. --main = print $ take 10 $ tape $ ((loop seld) . modi) newMachine
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement