2016-11-07 28 views
2

這甚至可能嗎?我有一個主要保存由用戶給出的Int(寬度)作爲變量,但我需要在一堆其他函數中的變量...有沒有辦法做到這一點,而不是添加'寬度'作爲參數每個功能?使從整個代碼可訪問的輸入變量

+0

的[哈斯克爾 - 模擬全局變量(函數)可能的複製(http://stackoverflow.com/questions/16811376/haskell-simulate-global-variablefunction) – Rakete1111

+0

@ Rakete1111 OP並不需要寫狀態,只讀。 – Alec

+0

@Alec但是你不能在Haskell中改變變量,對吧?儘管如此,OP需要將來自用戶的輸入寫入其中。 – Rakete1111

回答

3

我將展示一個閱讀器monad用法的簡單示例。

此代碼:

area :: Double -> Double -> Double 
area height width = height * width 

main = do 
    width <- fmap read getLine 
    let result = area 42 width 
    print result 

變爲:

import Control.Monad.Reader 

area :: MonadReader Double m => Double -> m Double 
area height = do 
    width <- ask 
    return (width * height) 

main :: IO() 
main = do 
    width <- fmap read getLine 
    let result = runReader (area 42) width 
    print result 

這似乎更復雜,但它實際上是相當不錯的,當你有很多的「配置」參數傳遞左右。

import Control.Monad.Reader 

data Config = Config { width :: Double, color :: String, etc :: String } 

area :: MonadReader Config m => Double -> m Double 
area height = do 
    w <- asks width 
    return (w * height) 

main :: IO() 
main = do 
    w <- fmap read getLine 
    c <- undefined -- todo get color param 
    e <- undefined -- todo get etc param 
    let result = runReader (area 42) (Config w c e) 
    print result 
相關問題