Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 获取索引“处的元素”;elemIndex“;列表中_Haskell - Fatal编程技术网

Haskell 获取索引“处的元素”;elemIndex“;列表中

Haskell 获取索引“处的元素”;elemIndex“;列表中,haskell,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] ->

基本上,我试图使用
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
我已经试过
!!运算符
但它只接受Int,因此我添加了函数
getIntAtIndex
,以实现这一点。 有人能告诉我错误在哪里吗?因为我看不见

我希望
getAge“Jack”names
返回
1
getAge“Bill”names
返回
Nothing


谢谢

如果您想使用
作为中缀运算符,您需要将其环绕在背景符号中。GHC认为
不存在n
正在应用于函数


另外,您可能希望
(| |)为:Bool->Bool->Bool
而不是
或::[Bool]->Bool

Haskell不是Python。布尔OR的短路运算符是
|
,而不是
(这是一个函数)。即使我们将
(isNothing n)或(n<0)
写成
(isNothing n)|(n<0)
这仍然是错误的:第一部分要求
n
可能是某物
,而第二部分要求
n
是数字,例如
Int
。这两种类型不兼容。我会避免使用
isNothing
并使用模式匹配,例如
getIntAtIndex Nothing[]=…
。我必须补充一点,我不明白为什么要传递索引的
Maybe Int
:我会使用一个普通的
Int
。谢谢你的输入
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.