为什么不创建一个脚本前端来编译脚本,如果它以前没有或者编译的版本已经过时了。
这是基本的想法,这段代码可以改进很多——搜索路径而不是假设所有内容都在同一个目录中,更好地处理其他文件扩展名,等等。而且我在 haskell 编码(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
现在我们可以创建这样的脚本(hs-echo.hs):
#! ghc-compiled-script
import Data.List
import System
import System.Environment
main = do
  args <- getArgs
  putStrLn $ foldl (++) "" $ intersperse " " args
现在运行它:
$ 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