我知道我可以使用函數單子來實現類似下面的一個結構(在這裏我重複使用多次調用的參數不明確引用它)之前執行轉換到輸入:應用功能單子
compute_v0 :: String -> String
compute_v0 = do
x <- length -- (using the argument implicitly here)
top <- head -- (and here)
return (replicate x top)
對上述函數的結果:compute "1234"
將"1111"
我的問題是:我將如何執行做塊之前應用轉換到「隱藏」的說法(想象一下,我想追加「ABCD 「到列表中)。
我的第一個解決方案:
compute_v1 :: String -> String
compute_v1 = compute_v1' . (++ "abcd")
compute_v1' ::String -> String
compute_v1' = do
x <- length
top <- head
return (replicate x top)
爲compute "1234"
結果現在是"11111111"
。這實際上完成了這項工作,但我寧願將它全部定義在一個簡潔的代碼塊中。
我能得到的最接近實際包括同時仍保持與代碼(V0)的風格改造這一項:
compute_v2 :: String -> String
compute_v2 = (++ "abcd") >>= \r -> do
let x = length r
let top = head r
return $ replicate x top
但我還是必須包括一個拉姆達,使用了大量的let綁定的並明確引用lambda參數。有更好的方法來實現這樣的結構嗎?
'compute_v1 = liftA2重複長度頭。 (++「abcd」)' – 4castle
'compute_v1 =(複製<$>長度<*>頭)。 (++「abcd」)' – Redu