Haskell - 无法理解一小段代码

时间:2017-09-09 13:38:44

标签: list class dictionary haskell anonymous-function

我正在做一个学校任务,我会收到一些示例代码,稍后我可以使用。我理解这段代码的90%,但有一条小线/功能,我在生活中无法弄清楚它是做什么的(我对Haskell btw很新)。

示例代码:

data Profile = Profile {matrix::[[(Char,Int)]], moleType::SeqType, nrOfSeqs::Int, nm::String} deriving (Show)

nucleotides = "ACGT"
aminoacids = sort "ARNDCEQGHILKMFPSTWYVX"

makeProfileMatrix :: [MolSeq] -> [[(Char, Int)]]
makeProfileMatrix [] = error "Empty sequence list"
makeProfileMatrix sl = res
  where 
    t = seqType (head sl)
    defaults = 
      if (t == DNA) then
        zip nucleotides (replicate (length nucleotides) 0) -- Row 1
      else 
        zip aminoacids (replicate (length aminoacids) 0)   -- Row 2
    strs = map seqSequence sl                              -- Row 3
    tmp1 = map (map (\x -> ((head x), (length x))) . group . sort)
               (transpose strs)                            -- Row 4
    equalFst a b = (fst a) == (fst b)
    res = map sort (map (\l -> unionBy equalFst l defaults) tmp1)

{-Row 1: 'replicate' creates a list of zeros that is equal to the length of the 'nucleotides' string. 
This list is then 'zipped' (combines each element in each list into pairs/tuples) with the nucleotides-}

{-Row 2: 'replicate' creates a list of zeros that is equal to the length of the 'aminoacids' string.
This list is then 'zipped' (combines each element in each list into pairs/tuples) with the aminoacids-}

{-Row 3: The function 'seqSequence' is applied to each element in the 'sl' list and then returns a new altered list. 
In other words 'strs' becomes a list that contains the all the sequences in 'sl' (sl contains MolSeq objects, not strings)-}

{-Row 4: (transpose strs) creates a list that has each 'column' of sequences as a element (the first element is made up of each first element in each sequence etc.).
--}

我已经为代码中的每个标记行写了一个解释(我认为到目前为止是正确的)但是当我试图弄清楚Row 4的作用时我会陷入困境。我理解'转置'位,但我根本无法弄清楚内部映射函数的作用。据我所知,'map'函数需要一个列表作为第二个参数才能运行,但内部map函数只有一个匿名函数,但没有要操作的列表。要完全清楚,我不明白整个内线map (\x -> ((head x), (length x))) . group . sort的作用。请帮忙!

加成:!

这是另一段我无法弄清楚的示例代码(从未使用过Haskell中的类):

class Evol object where
 name :: object -> String
 distance :: object -> object -> Double
 distanceMatrix :: [object] -> [(String, String, Double)]
 addRow :: [object] -> Int -> [(String, String, Double)]
 distanceMatrix [] = []
 distanceMatrix object =
  addRow object 0 ++ distanceMatrix (tail object)
 addRow object num  -- Adds row to distance matrix
  | num < length object = (name a, name b, distance a b) : addRow object (num + 1)
  | otherwise = [] 
  where  
        a = head object
        b = object !! num


 -- Determines the name and distance of an instance of "Evol" if the instance is a "MolSeq".
instance Evol MolSeq where
 name = seqName
 distance = seqDistance

 -- Determines the name and distance of an instance of "Evol" if the instance is a "Profile".
instance Evol Profile where
 name = profileName
 distance = profileDistance

特别是这部分:

addRow object num  -- Adds row to distance matrix
  | num < length object = (name a, name b, distance a b) : addRow object (num + 1)
  | otherwise = [] 
  where  
        a = head object
        b = object !! num

如果你不想这样做,你不必解释这一点我只是稍微混淆了'addRow'实际上正在尝试做什么(详细)。

谢谢!

2 个答案:

答案 0 :(得分:4)

map (\x -> (head x, length x)) . group . sort是生成直方图的惯用方法。当你看到这样你不理解的东西时,试着将它分解成更小的部分并在样本输入上测试它们:

(\x -> (head x, length x)) "AAAA"
-- ('A', 4)

(group . sort) "CABABA"
-- ["AAA", "BB", "C"]

(map (\x -> (head x, length x)) . group . sort) "CABABA"
map (\x -> (head x, length x)) (group (sort "CABABA"))
-- [('A', 3), ('B', 2), ('C', 1)]

它以无点样式编写,由3个函数map (…)groupsort组成,但也可以写成拉姆达:

\row -> map (…) (group (sort row))

对于转置矩阵中的每一行,它会生成该行中数据的直方图。您可以通过格式化并打印出来来获得更直观的表示:

let
  showHistogramRow row = concat
    [ show $ head row
    , ":\t"
    , replicate (length row) '#'
    ]
  input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

putStr
  $ unlines
  $ map showHistogramRow
  $ group
  $ sort input

-- 1:   ##
-- 2:   #
-- 3:   ##
-- 4:   #
-- 5:   ###
-- 6:   #
-- 9:   #

至于此:

addRow object num  -- Adds row to distance matrix
  | num < length object = (name a, name b, distance a b) : addRow object (num + 1)
  | otherwise = [] 
  where  
        a = head object
        b = object !! num

addRow列出从object中的第一个元素到每个其他元素的距离。它以一种非显而易见的方式在列表中使用索引,当一个更简单且更惯用的map就足够了:

addRow object = map (\ b -> (name a, name b, distance a b)) object
  where a = head object

通常最好避免使用部分函数,例如head,因为它们可以在某些输入上引发异常(例如head [])。但是,这很好,因为如果输入列表为空,则永远不会使用a,因此永远不会调用head

distanceMatrix也可以用map表示,因为它只是在列表的所有addRow上调用函数(tails)并将它们连接在一起++

distanceMatrix object = concatMap addRow (tails object)

这也可以用无点样式编写。 \x -> f (g x)可以写为f . g;在这里,fconcatMap addRowgtails

distanceMatrix = concatMap addRow . tails

Evol只描述了您可以为其生成distanceMatrix的类型集,包括MolSeqProfile。请注意,addRowdistanceMatrix不需要是此类的成员,因为它们完全按照namedistance实现,因此您可以移动它们到顶级:

distanceMatrix :: (Evol object) => [object] -> [(String, String, Double)]
distanceMatrix = concatMap addRow . tails

addRow :: (Evol object) => [object] -> Int -> [(String, String, Double)]
addRow object = map (\ b -> (name a, name b, distance a b)) object
  where a = head object

答案 1 :(得分:3)

  

内部地图功能只有一个匿名功能,但没有列表可以在

上运行

鉴于f类型的函数a -> b -> c,它接受​​两个参数并返回类型c的值。如果使用一个参数调用f,则返回另一个类型为b -> c的函数,该函数将再获取一个参数并返回一个值。这称为currying。

这一行:

map (map (\x -> ((head x), (length x))) . group . sort) (transpose strs)

可以转化为:

map (\str -> (map (\x -> ((head x), (length x))) . group . sort) str)(transpose strs)

在这种形式中,它可能会被清除,实际上是一个可以操作的列表。

此功能

(map (\x -> ((head x), (length x))) . group . sort)

只是sortgroupmap (\x -> ((head x), (length x)))的组合。

让我们看看[2,1,1,1,4]

的工作原理

sort [2, 1, 1, 1, 4] =&gt; [1, 1, 1, 2, 4]

group [1, 1, 1, 2, 4] =&gt; [[1,1,1],[2],[4]]

map (\x -> ((head x), (length x))) =&gt; [(1,3),(2,1),(4,1)]

它只返回一个元组列表。每个元组都包含一个元素作为第一个元素,并将出现次数作为第二个元素。