从列表列表中取出第n个列表

时间:2014-12-01 23:44:30

标签: list haskell matrix tuples extract

我有以下函数返回对列表的列表。

getprofileMatrix :: Profile -> [[(Char, Int)]]
getprofileMatrix (Profile profileMatrix _ _ _) = profileMatrix

我想要做的是创建一个获取ProfileIntChar值的函数,然后查看列表[[(Char, Int)]]并返回第n个list(Int参数值)看起来像这个[(Char,Int)],然后在元组列表中查找Char,如果我的参数Char值匹配,然后它返回该元组的Int值。

为了获得[(Char,Int)]列表的Int值,我构造了以下函数:

tupleNr :: Char -> [(Char, Int)] -> Int
tupleNr letter list = head [nr | (ltr, nr) <- list, ltr == letter]

此功能按预期工作。我的问题是尝试从[[(Char,Int]]中提取第n个列表,然后将tupleNr函数应用于它:

profileFrequency :: Profile -> Int -> Char -> Int
profileFrequency p i c = tupleNr c (map (\x -> (x !! i)).(getprofileMatrix p)) 

但它不起作用..我真的不明白为什么它不起作用。首先,我调用getprofileMatrix函数,该函数从[[(Char, Int])] Profile返回列表p。之后,它映射我的lambda函数以从列表中提取第i个元素,以便我得到单个列表[(Char, Int)]。之后,我应用tupleNr函数来获取Int列表的[(Char, Int)]值。我觉得这应该有效,但事实并非如此。

我收到以下错误:

  Couldn't match expected type ‘[(Char, Int)]’
                with actual type ‘a0 -> [b0]’
    In the second argument of ‘tupleNr’, namely
      ‘(map (\ x -> (x !! i)) . (getprofileMatrix p))’
    In the expression:
      tupleNr c (map (\ x -> (x !! i)) . (getprofileMatrix p))
    In an equation for ‘profileFrequency’:
        profileFrequency p i c
          = tupleNr c (map (\ x -> (x !! i)) . (getprofileMatrix p))


    Couldn't match expected type ‘a0 -> [[b0]]’
                with actual type ‘[[(Char, Int)]]’
    Possible cause: ‘getprofileMatrix’ is applied to too many arguments
    In the second argument of ‘(.)’, namely ‘(getprofileMatrix p)’
    In the second argument of ‘tupleNr’, namely
      ‘(map (\ x -> (x !! i)) . (getprofileMatrix p))’

很抱歉,如果我不够清楚,但希望任何人都可以提供帮助!感谢。

1 个答案:

答案 0 :(得分:1)

替换:

profileFrequency :: Profile -> Int -> Char -> Int
profileFrequency p i c = tupleNr c (map (\x -> (x !! i)).(getprofileMatrix p))

使用:

profileFrequency :: Profile -> Int -> Char -> Int
profileFrequency p i c = tupleNr c . map (!! i) . getprofileMatrix $ p
--                                 ^1    ^^^^^^2                  ^^^3

问题是:

  1. 函数应用程序优先于组合,因此在tupleNr c (map (\x -> (x !! i))中,您传递(map (\x -> (x !! i))这是一个函数,作为tupleNr的“第二个参数”,它接受一个列表而不是。你想要的是改为组成tupleNr c(map (\x -> (x !! i))

  2. 不是真正的问题,但map (\x -> (x !! i)相当于map (!! i),因此您可以对其进行重构。这与(+ 1) (\i -> i + 1)的概念相同。

  3. 最后,您想要的是将p传递给撰写的函数(tupleNr c . map (!! i) . getprofileMatrix)。这不是你在做什么:(getprofileMatrix p)属于[[(Char, Int)]]类型,它不是函数类型,因此你无法编写它。因此,在编写完所有函数后,您必须将p的应用程序延迟。

相关问题