已经提出并回答了几个类似的问题。可以找到实例,例如:
但是,我所发现的东西都没有完全回答我的问题。
在Haskell中,是否可能以及如何定义一个函数cartesianProduct,该函数任意(有限)地获取许多不同类型的列表,并在鼻子上输出其笛卡尔积?
例如,在上面的链接中,可以找到一个cartesianProd_2优雅地吸收两个不同类型列表的列表:
cartesianProd_2 :: [a] -> [b] -> [(a,b)]
cartesianProd_2 list_A list_B = [(x,y) | x<-list_A, y<-list_B]
Run Code Online (Sandbox Code Playgroud)
cartesianProd_n对于某些固定整数n,可以很容易地将其推广为。
但是,我希望我可以定义一个
cartesianProd (list_1,list_2) == (cartesianProd_2 list_1 list_2)
cartesianProd (list_1,list_2,list_3) == (cartesianProd_3 list_1 list_2 list_3)
-- and so on .. notice that list_i is a list of elements of type i.
Run Code Online (Sandbox Code Playgroud)
一个直接的障碍,我遇到的是,我甚至不知道是什么类型的cartesianProd啊!它的域是(不同类型的列表)的元组!那我该怎么办?
如果在Haskell中无法做到,请提供(指向)指针。
Haskell newbie here. I use ghci to implement a baby quicksort algorithm [1] as follows:
Prelude> quicksort (firstx:xs) = quicksort[x|x<-xs, x<firstx] ++ [firstx] ++ quicksort[x|x<-xs, not(x<firstx)]
Prelude> quicksort [] = []
Run Code Online (Sandbox Code Playgroud)
The command quicksort [1,2,3] then gives an error:
*** Exception: :8:1-17: Non-exhaustive patterns in function quicksort
However, typing the exact same thing in an quicksort.hs file and running $ ghci quicksort.hs do not yield such an error.
What makes the difference? Is it a rule of thumb that …