工作需要写了第一个简单的haskell程序,练手
博客专区 > Kyli 的博客 > 博客详情
工作需要写了第一个简单的haskell程序,练手
Kyli 发表于1年前
工作需要写了第一个简单的haskell程序,练手
  • 发表于 1年前
  • 阅读 34
  • 收藏 0
  • 点赞 0
  • 评论 0
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}

module Main where

import Options.Applicative
import System.Environment
import System.Exit
import System.IO
import System.Directory
import System.FilePath
import Control.Exception
import qualified Data.Map.Lazy as DM
-- import qualified Date.ByteString.Lazy as BL
import Control.Monad (mapM_)


data MyArgs = MyArgs
  { dir :: FilePath
  , ref :: FilePath }

margs :: Parser MyArgs
margs = MyArgs
  <$> strOption
  (
    long "directory"
    <> short 'd'
    <> metavar "DIR"
    <> help "Directory that contains the downloaded files"
  )
  <*> strOption
  (
    long "reference"
    <> short 'r'
    <> metavar "REF"
    <> help "Reference file that contains the original names and new names"
  )

renameDownloads :: MyArgs -> IO ()
renameDownloads MyArgs {..} = do
  putStrLn $ "Rename maps: " ++ ref
  putStrLn $ "Source directory: " ++ dir
  r         <- getRenameRef ref
  fnames    <- getDirectoryContents dir
  let rnMap = DM.fromList r
  rename dir rnMap fnames
  putStrLn "Finished"

rename :: FilePath -> DM.Map FilePath String -> [FilePath] -> IO ()
rename dir renameMap = mapM_ rename'
  where rename' filename = case DM.lookup filename renameMap of
                             Nothing -> return ()
                             Just val -> renameFile (dir </> filename) (dir </> val)

getRenameRef :: FilePath -> IO [(FilePath, String)]
getRenameRef fpath = do
  h <- openFile fpath ReadMode
  hSetEncoding h utf8
  contents <- hGetContents h
  parse contents
  where
    parse = return . alist . parse'
    parse' = map words . lines
    alist = convert2alist . filterValidPath
    filterValidPath = filter (\inp -> case inp of
                                     (x:xs) -> True
                                     _ -> False
                                 )
    convert2alist = map (\(x:xs) -> (x, unwords xs))

main :: IO ()
main = execParser opts >>= renameDownloads
  where opts = info (helper <*> margs)
               (
                 fullDesc
                 <> progDesc "Batch rename the audio files downloaded from xxxxxxx"
               )

批量重命名,直接贴代码吧,写ruby的码农朋友说“这他么看也看不懂,是猴子写的吗?”

不得不说,Option.Applicative真心不错,貌似社区也是大力推荐,

没有用monad之类的,基本上就是很简单的逻辑,只是为了习惯了一下haskell的写法,连错误处理没有ADT也没有,所以,just a toy,只是为了满足需求

 

标签: Haskell
共有 人打赏支持
粉丝 5
博文 25
码字总数 4526
×
Kyli
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: