如何将Haskell System.Directory getHomeDirectory转换为常规字符串?

Eri*_*ius 1 haskell xmonad

我是Haskell noob,目前只使用它来配置xmonad.

我想将我的配置放入一个git仓库,因为我不想硬编码我的家庭目录来抓住我的图标.

我查看了 http://www.haskell.org/haskellwiki/How_to_get_rid_of_IO, 但我太无知了解它.

hd h = h =<< getHomeDirectory

getIcon::String -> String
getIcon out = ( "^i("++hd++".xmonad/dzen2/"++out )
Run Code Online (Sandbox Code Playgroud)

这有可能吗?如果是这样,怎么样?我不想在目录上操作,我只想要路径,作为一个字符串,它杀了我.

错误是:

Couldn't match expected type `[Char]'
            with actual type `(FilePath -> IO b0) -> IO b0'
In the first argument of `(++)', namely `hd'
In the second argument of `(++)', namely
  `hd ++ ".xmonad/dzen2/" ++ out'
In the expression: ("^i(" ++ hd ++ ".xmonad/dzen2/" ++ out)
Run Code Online (Sandbox Code Playgroud)

在我看来,IO monad根本没有删除.

更新:好的.我将学习如何适应IO规则,在此之前我将保持硬编码并使用将替换相应位的脚本克隆配置文件.

Don*_*art 6

getIcon的类型错误,因为getHomeDirectoryIO:

getIcon :: String -> IO String
getIcon out = do
     hd <- getHomeDirectory
     return $ "^i(" ++ hd ++ ".xmonad/dzen2/" ++ out
Run Code Online (Sandbox Code Playgroud)

请记住,Haskell通过类型区分具有副作用的代码 - 例如读取硬盘IO.

所以调用者也会在IO中:

main = do
    s <- getIcon "foo"
    .. now you have a regular string 's' ...
Run Code Online (Sandbox Code Playgroud)

  • @Erius没有类型`IO String - > String`的(安全)Haskell函数."IO"中发生的事情仍然存在于"IO"中. (4认同)