Haskell括号

时间:2018-03-04 23:20:59

标签: haskell

有没有人可以帮我纠正和理解为什么以下语法有效?我想这是括号问题。

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]

由于

1 个答案:

答案 0 :(得分:3)

#include <stdio.h> void gswap(void* ptra, void* ptrb, int size) { char temp; char *pa = (char*)ptra; char *pb = (char*)ptrb; for (int i = 0 ; i < size ; i++) { temp = pa[i]; pa[i] = pb[i]; pb[i] = temp; } } int main() { int a=1, b=5; gswap(&a, &b, sizeof(int)); printf("%d , %d", a, b) } 表示“使用6个参数调用findMinMaxRec head myList head myList tail myListfindMinMaxRecheadmyListheadmyList,和tail“。你想要:

myList

但是,最好避免使用模式匹配findMinMaxRec (head myList) (head myList) (tail myList) head - 这里有一点点改进:

tail

同样,当你写:

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] 仅在0元素(findMinMax)和1元素([])列表中定义;它与括号有同样的问题。另一个小调整:

[x]

最后,由于findMinMax [] = [] findMinMax (x:xs) = findMinMaxRec x x xs 总是返回一个双元素列表,因此返回类型最好使用元组;然后findMinMaxRec可以返回findMinMax