【问题标题】:Haskell parentheses哈斯克尔括号
【发布时间】:2018-03-04 23:20:59
【问题描述】:

谁能帮我纠正和理解为什么下面的语法不起作用?我想这是括号的问题。

findMinMaxRec smallest largest myList
  | myList == [] = [smallest, largest]
  | head myList < smallest && head myList > largest = findMinMaxRec head myList head myList tail myList 
  | head myList < smallest = findMinMaxRec head myList largest tail myList 
  | head myList > largest = findMinMaxRec smallest head myList tail myList 
  | otherwise = findMinMaxRec smallest largest tail myList

findMinMax [] = []
findMinMax [x] = findMinMaxRec head [x] head [x] [x]

谢谢

【问题讨论】:

  • 通过在任何地方使用 head 而不是正确的模式匹配,你真的让它变得非常复杂和不可读:(
  • 除了head/tail 的问题(几乎永远不应该使用)之外,请确保您始终使用类型签名并根据子表达式的类型来考虑代码>.
  • 以后,在问题中包含编译器错误。

标签: haskell


【解决方案1】:

findMinMaxRec head myList head myList tail myList 表示“使用 6 个参数调用 findMinMaxRecheadmyListheadmyListtailmyList”。你想要:

findMinMaxRec (head myList) (head myList) (tail myList)

但是,最好避免 headtail 使用模式匹配——这里有一点改进:

findMinMaxRec smallest largest [] = [smallest, largest]
findMinMaxRec smallest largest (x:xs)
  | x < smallest && x > largest = findMinMaxRec x x xs
  | x < smallest = findMinMaxRec x largest xs
  | x > largest = findMinMaxRec smallest x xs
  | otherwise = findMinMaxRec smallest largest xs

同样,当你写作时:

findMinMax [] = []
findMinMax [x] = findMinMaxRec head [x] head [x] [x]

这意味着 findMinMax 仅在 0 元素 ([]) 和 1 元素 ([x]) 列表中定义;括号也有同样的问题。另一个小调整:

findMinMax [] = []
findMinMax (x:xs) = findMinMaxRec x x xs

最后,由于findMinMaxRec 总是返回一个二元素列表,所以返回类型最好使用元组;那么findMinMax 可以返回一个Maybe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多