获取元素索引" elemIndex"在列表中

时间:2015-10-27 18:57:16

标签: haskell

基本上我试图使用elementIndex函数中的值来获取列表中的第n个元素。 这是我的代码:

import Data.List
import Data.Maybe

names = ["Molly", "Jack", "Perrie", "Adele", "Jake", "Lily", "Lawrence", "Ethan"] :: [String]
ages = [5,1,8,9,6,4,7,3] :: [Int]

getAge :: String -> [String] -> [Int] -> Maybe Int
getAge name names ages = getIntAtIndex index ages
    where
        index = elemIndex name names

getIntAtIndex :: Maybe Int -> [Int] -> Maybe Int
getIntAtIndex n [] = Nothing
getIntAtIndex n (x:xs)
        | (isNothing n) or (n < 0) = Nothing
        | n == 0 = Just x
        | otherwise = getIntAtIndex (n-1) xs

getAge搜索name中的names,并从index中的同一ages返回年龄。 但当我尝试在ghci加载文件时,我得到:

Prelude> :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )

test.hs:15:11:
    Couldn't match expected type `(t0 Bool -> Bool) -> Bool -> Bool'
                with actual type `Bool'
    The function `isNothing' is applied to three arguments,
    but its type `Maybe Int -> Bool' has only one
    In the expression: (isNothing n) or (n < 0)
    In a stmt of a pattern guard for
                   an equation for `getIntAtIndex':
      (isNothing n) or (n < 0)
Failed, modules loaded: none.

我已经尝试了!! operator,但它只接受了Int,所以我添加了函数getIntAtIndex以实现此目的。 有人能指出我的错误在哪里?因为我无法看到它。

我希望getAge "Jack" names返回1getAge "Bill" names返回Nothing

由于

1 个答案:

答案 0 :(得分:2)

如果您想将or用作中缀运算符,则需要将其包围在反引号中。 GHC认为isNothing n正在应用于or函数。

此外,您可能希望(||) :: Bool -> Bool -> Bool不是or :: [Bool] -> Bool