基本上我试图使用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
返回1
和getAge "Bill" names
返回Nothing
由于
答案 0 :(得分:2)
如果您想将or
用作中缀运算符,则需要将其包围在反引号中。 GHC认为isNothing n
正在应用于or
函数。
此外,您可能希望(||) :: Bool -> Bool -> Bool
不是or :: [Bool] -> Bool