Ad
Fundamentals
Functional Programming

a haskell code

Code
Diff
  • module NumberPrint where
    
    import Control.Monad         (when)
    import Data.IORef            (newIORef)
    import Data.StateVar         (($=), ($~), get)
    import Foreign.Ptr           (Ptr (..))
    import Foreign.Marshal.Alloc (alloca)
    import System.IO.Unsafe      (unsafePerformIO)
    
    whileM :: Monad m => m Bool -> m () -> m ()
    whileM mb a = do
      b <- mb
      when b $ a >> whileM mb a
    
    numberprint :: Int -> Integer
    numberprint n = read . unsafePerformIO $ do 
      alloca $ \(i :: Ptr Int)-> do
        i $= 1
        s <- newIORef ""
        whileM ((<n) <$> get i) $ do
          c <- get i
          s $~ (show c++)
          i $~ (1+)
        whileM ((>= 1) <$> get i) $ do
          c <- get i
          s $~ (show c++)
          i $~ (-1+)
        get s
     
    • module NumberPrint where
    • import Control.Monad (when)
    • import Data.IORef (newIORef)
    • import Data.StateVar (($=), ($~), get)
    • import Foreign.Ptr (Ptr (..))
    • import Foreign.Marshal.Alloc (alloca)
    • import System.IO.Unsafe (unsafePerformIO)
    • whileM :: Monad m => m Bool -> m () -> m ()
    • whileM mb a = do
    • b <- mb
    • when b $ a >> whileM mb a
    • numberprint :: Int -> Integer
    • numberprint = read . (>>= id) . ((++) <*> (reverse . init)) . (\x -> show <$> [1..x])
    • numberprint n = read . unsafePerformIO $ do
    • alloca $ \(i :: Ptr Int)-> do
    • i $= 1
    • s <- newIORef ""
    • whileM ((<n) <$> get i) $ do
    • c <- get i
    • s $~ (show c++)
    • i $~ (1+)
    • whileM ((>= 1) <$> get i) $ do
    • c <- get i
    • s $~ (show c++)
    • i $~ (-1+)
    • get s
Code
Diff
  • module AddNumbers where
    import Data.Monoid( Sum(..) )
    
    add_arr :: [Int] -> Int
    add_arr = getSum . foldMap Sum
    • module AddNumbers where
    • add_arr x = sum x
    • import Data.Monoid( Sum(..) )
    • add_arr :: [Int] -> Int
    • add_arr = getSum . foldMap Sum