-
FundamentalsFunctional Programming
Description a haskell code
Code 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
Test Cases module NumberPrintSpec where import Test.Hspec import NumberPrint spec :: Spec spec = do describe "Tests" $ do it "Fixed Tests" $ do numberprint 1 `shouldBe` 1 numberprint 2 `shouldBe` 121 numberprint 10 `shouldBe` 12345678910987654321 main = hspec spec
Output:
-
Code - 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
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}