Is there a quick-starting Haskell interpreter suitable for scripting?

前端 未结 5 1426
生来不讨喜
生来不讨喜 2021-02-01 06:49

Does anyone know of a quick-starting Haskell interpreter that would be suitable for use in writing shell scripts? Running \'hello world\' using Hugs took 400ms on my old laptop

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 07:28

    Why not create a script front-end that compiles the script if it hasn't been before or if the compiled version is out of date.

    Here's the basic idea, this code could be improved a lot--search the path rather then assuming everything's in the same directory, handle other file extensions better, etc. Also i'm pretty green at haskell coding (ghc-compiled-script.hs):

    import Control.Monad
    import System
    import System.Directory
    import System.IO
    import System.Posix.Files
    import System.Posix.Process
    import System.Process
    
    getMTime f = getFileStatus f >>= return . modificationTime
    
    main = do
      scr : args <- getArgs
      let cscr = takeWhile (/= '.') scr
    
      scrExists <- doesFileExist scr
      cscrExists <- doesFileExist cscr
      compile <- if scrExists && cscrExists
                   then do
                     scrMTime <- getMTime scr
                     cscrMTime <- getMTime cscr
                     return $ cscrMTime <= scrMTime
                   else
                       return True
    
      when compile $ do
             r <- system $ "ghc --make " ++ scr
             case r of
               ExitFailure i -> do
                       hPutStrLn stderr $
                                "'ghc --make " ++ scr ++ "' failed: " ++ show i
                       exitFailure
               ExitSuccess -> return ()
    
      executeFile cscr False args Nothing
    

    Now we can create scripts such as this (hs-echo.hs):

    #! ghc-compiled-script
    
    import Data.List
    import System
    import System.Environment
    
    main = do
      args <- getArgs
      putStrLn $ foldl (++) "" $ intersperse " " args
    

    And now running it:

    $ time hs-echo.hs "Hello, world\!"     
    [1 of 1] Compiling Main             ( hs-echo.hs, hs-echo.o )
    Linking hs-echo ...
    Hello, world!
    hs-echo.hs "Hello, world!"  0.83s user 0.21s system 97% cpu 1.062 total
    
    $ time hs-echo.hs "Hello, world, again\!"
    Hello, world, again!
    hs-echo.hs "Hello, world, again!"  0.01s user 0.00s system 60% cpu 0.022 total
    

提交回复
热议问题