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.