我已經在過去一次寫入以下函數來將列表中的整數x的任何實例替換爲另一個整數y。這裏是我的代碼:如何更改此函數以使用任何類型,而不僅僅是Int
substitute::Int->Int->[Int]->[Int]
substitute x y [] =[]
substitute x y (z:zs)
|(z==x) =y:substitute x y (zs)
|otherwise =z:substitute x y (zs)
下面是一個示例調用:
main = do
print $ substitute 2 3 [2, 2, 2]
我現在想與任何類型的輸入此代碼的工作。所以我嘗試將參數類型轉換爲通用的「a」,但是它會吐出一個錯誤,因爲Haskell認爲它是某種習慣的高階函數。那麼,如何使這項工作:找出
substitute::a->a->[a]->[a]
substitute x y [] =[]
substitute x y (z:zs)
|(z==x) =y:substitute x y (zs)
|otherwise =z:substitute x y (zs)
main = do
print $ substitute 2 'a' [2, 2, 2]
在您的下一個問題中,請始終發佈錯誤。它通常會幫助讀者,並提高你得到答案的機會。 – chi 2014-12-02 09:41:37