小编Bea*_*row的帖子

使用下面的函数查找元组中的第 n 个元素

“使用以下带有两个参数的函数:

nth :: (a,a,a,a,a) -> Int -> a
Run Code Online (Sandbox Code Playgroud)

其中 Int 值应返回五元素元组的第 Int 值。”我尝试过:

nth (a,b,c,d,e) x = (a,b,c,d,e) !! x
Run Code Online (Sandbox Code Playgroud)

但 GHC 给了我一条错误消息:

file.hs:11:21: error:
* Couldn't match expected type `[a1]'
              with actual type `(a, b, c, d, e)'
* In the first argument of `(!!)', namely `(a, b, c, d, e)'
  In the expression: (a, b, c, d, e) !! x
  In an equation for `nth':
      nth (a, b, c, d, e) x = (a, b, c, d, e) …
Run Code Online (Sandbox Code Playgroud)

haskell tuples

6
推荐指数
2
解决办法
441
查看次数

无法将预期类型“Bool”与实际类型“a -> Bool”匹配

我想编写一个返回列表的最长前缀的函数,其中将函数应用于该前缀中的每个项目会生成一个严格升序的列表。

例如:

最长的升序前缀 (`mod` 5) [1..10] == [1,2,3,4]

最长升序前缀奇数 [1,4,2,6,8,9,3,2,1] == [1]

longestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]
longestAscendingPrefix _ [] = []
longestAscendingPrefix f (x:xs) = takeWhile (\y z -> f y <= f z) (x:xs)
Run Code Online (Sandbox Code Playgroud)

此代码片段产生标题中的错误消息。问题似乎出在 lambda 函数上。

haskell function

4
推荐指数
1
解决办法
318
查看次数

返回一个列表,其中包含一对元素,但前提是各个元素的总和为奇数

实现oddPairs :: [Int] -> [Int] -> [(Int, Int)]返回对列表的函数,但前提是参数列表各自元素的总和为奇数。

例如:

oddPairs [1,2,3] [2,2,2] == [(1,2),(3,2)]

oddPairs [1,3,5] [2,4,6] == zip [1,3,5] [2,4,6]

oddPairs [1,2,3] [1,2,3] == []

到目前为止,我已经尝试过

oddPairs (x:xs) (y:ys) | (x+y) `mod` 2 == 0 = []
                       | (x+y) `mod` 2 /= 0 = [(x, y)] ++ oddPairs (xs) (ys)
Run Code Online (Sandbox Code Playgroud)

在第一个示例中,它仅返回[(1,2)],在第二个示例中,它返回正确的值,但有Non-exhaustive patterns错误。

recursion haskell modulo

3
推荐指数
1
解决办法
716
查看次数

标签 统计

haskell ×3

function ×1

modulo ×1

recursion ×1

tuples ×1