[英]How do I use map to generalize a function
我正在嘗試設計一個Haskell程序來構建一個游戲理論樹,該樹通過重復玩基礎游戲(小G)指定次數來創建游戲(資本G)。
下面的foo函數可以通過將基礎游戲的每個結果/收益添加一個回合的結果(或收益)來正常工作。 一個主要限制是基本游戲被永久設置為具有三個結果。
foo'函數(不起作用)應該是foo函數的概括。 那就是通過使用map函數和代表基本游戲的值列表來模仿foo函數。
data MyTree a = Root a [MyTree a] | Branch a [MyTree a] | Leaf a | EmptyNode deriving Show
x1:: Integer
x1 = 1
x2 :: Integer
x2 = 25
x3 :: Integer
x3 = 100
foo :: [Integer] -> MyTree [Integer]
foo [r, a]
| r == 0 = Leaf [a]
| a == 0 = Root [a] [foo [r-1, a+x1], foo [r-1, a+x2], foo [r-1, a+x3]]
| otherwise = Branch [a] [foo [r-1, a+x1], foo [r-1, a+x2], foo [r-1, a+x3]]
lst = [x1, x2, x3]
foo' :: [Integer] -> MyTree [Integer]
foo' [r, a]
| r == 0 = Leaf [a]
| a == 0 = Root [a] map (foo'.(\y ->[r-1, y]).(\x -> a+x)) lst
| otherwise = Branch [a] map (foo'.(\y ->[r-1, y]).(\x -> a+x)) lst
出現以下錯誤兩次( a == 0行和其他行一個)。 我只列出了它們一次,因為一旦知道如何解決錯誤,就可以修復其重復項。
我收到的錯誤消息是(a)和(b):
Couldn't match expected type ‘([Integer] -> MyTree [Integer]) -> [[Integer]] -> MyTree [Integer]’with actual type ‘MyTree [Integer]’
Couldn't match expected type ‘[MyTree [Integer]]’with actual type ‘(a0 -> b0) -> [a0] -> [b0]’
我的問題是:如何獲得實際輸入以匹配預期輸入? 我花了很多天和時間研究語法,並在Google上搜索解決方案。
問題恰恰是編譯器說的:
函數“ Root”適用於四個參數,但其類型“ [Integer]-> [MyTree [Integer]]-> MyTree [Integer]”只有兩個
這是因為編譯器假定[a]
, map
, (foo'.(\\y ->[r-1, y]).(\\x -> a+x))
和lst
是函數Root
四個獨立參數。
可以通過使用$
來固定它,它設置了評估的優先級
foo' :: [Integer] -> MyTree [Integer]
foo' [r, a]
| r == 0 = Leaf [a]
| a == 0 = Root [a] $ map (foo'.(\y ->[r-1, y]).(\x -> a+x)) lst
| otherwise = Branch [a] $ map (foo'.(\y ->[r-1, y]).(\x -> a+x)) lst
或者,因為可以將其移到單獨的函數中(可能genList
名稱不合適,所以當然可以組成一個更好的函數):
foo' :: [Integer] -> MyTree [Integer]
foo' [r, a]
| r == 0 = Leaf [a]
| a == 0 = Root [a] genList
| otherwise = Branch [a] genList
where genList = map (foo'.(\y ->[r-1, y]).(\x -> a+x)) lst
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.