具有两个功能的 fmap

fmap with two functions

我正在使用 haskell 编写神经网络。我的代码基于此 http://www-cs-students.stanford.edu/~blynn/haskell/brain.html 。 我按以下方式调整了前馈方法:

feedForward :: [Float] -> [([Float], [[Float]])] -> [Float]
feedForward = foldl ((fmap tanh . ) . previousWeights)

previousWeights 是:

previousWeights :: [Float] -> ([Float], [[Float]]) -> [Float]
previousWeights actual_value (bias, weights) = zipWith (+) bias (map (sum.(zipWith (*) actual_value)) weights)

我不太明白fmap tanh .从我读到的fmap应用于两个函数就像一个组合。如果我将 fmap 更改为 map,我会得到相同的结果。

如果我们给出参数名称并删除连续的 .:

会更容易阅读
feedForward :: [Float] -> [([Float], [[Float]])] -> [Float]
feedForward actual_value bias_and_weights =
  foldl
  (\accumulator -- the accumulator, it is initialized as actual_value
    bias_and_weight -> -- a single value from bias_and_weights
     map tanh $ previousWeights accumulator bias_and_weight)
  actual_value -- initialization value
  bias_and_weights -- list we are folding over

在这种情况下,了解 foldl 的类型签名将是 ([Float] -> ([Float], [[Float]])-> [Float]) -> [Float] -> [([Float], [[Float]])] -> [Float]

可能也会有所帮助

注意:您发现的这种代码风格虽然写起来很有趣,但对其他人阅读来说可能是一个挑战,如果不是为了好玩,我通常不建议您这样写。