2017-08-04 6 views
1

マップは以下では動作しませんなぜ私が特に知りたいん:RankNTypes in haskell。リスト内包は動作しますが、マップがない

{-# Language RankNTypes #-} 
module Demo where 
import Numeric.AD 

newtype Fun = Fun (forall a. Num a => [a] -> a) 

test1 :: Fun 
test1 = Fun $ \[u, v] -> (v - (u * u * u)) 

test2 :: Fun 
test2 = Fun $ \ [u, v] -> ((u * u) + (v * v) - 1) 

works :: (Ord a, Num a) => [[a] -> [a]] 
works = [ grad f | Fun f <- fList ] 

fList :: [Fun] 
fList = [test1, test2] 

GHCiのにこれを引っ張って私は、次を得る:

*Demo> w = [ grad f | Fun f <- fList ] 
*Demo> map (\f -> f [1, 1]) w 
[[-3,1],[2,2]] 

それはうまく動作しますが、同じことをしなければならない限り、動作しません。何故なの?ここの問題は何ですか?

*Demo> map (\f -> grad (Fun f)) fList 
<interactive>:31:18: error: 
• Couldn't match expected type ‘f (Numeric.AD.Internal.Reverse.Reverse 
            s a) 
           -> Numeric.AD.Internal.Reverse.Reverse s a’ 
       with actual type ‘Fun’ 
• Possible cause: ‘Fun’ is applied to too many arguments 
    In the first argument of ‘grad’, namely ‘(Fun f)’ 
    In the expression: grad (Fun f) 
    In the first argument of ‘map’, namely ‘(\ f -> grad (Fun f))’ 
• Relevant bindings include 
    it :: [f a -> f a] (bound at <interactive>:31:1) 

<interactive>:31:22: error: 
• Couldn't match expected type ‘[a1] -> a1’ with actual type ‘Fun’ 
• In the first argument of ‘Fun’, namely ‘f’ 
    In the first argument of ‘grad’, namely ‘(Fun f)’ 
    In the expression: grad (Fun f) 

私が使用しているライブラリは、Haskellの広告ライブラリです:https://hackage.haskell.org/package/ad-4.3.4

乾杯!

答えて

4

これらは等価ではない。、最初のものは、おおよそ、fListから値を抽出

*Demo> [ grad f | Fun f <- fList ] 
*Demo> map (\f -> grad (Fun f)) fList 

xを言う、fFun f = xように選択し、その後、grad fを呼び出します。

fListから値を抽出し、f(!)という値を抽出し、Fun fを計算してgradに渡します。

したがって、最初はリスト要素からFunラッパーを削除し、2番目のラッパーは代わりにラッパーを追加します。リスト内包がするようにラッパーを削除します

*Demo> map (\ (Fun f) -> grad f) fList 

はそれを比較してください。

関連する問題