gol*_*enk 3 haskell list pattern-matching
我在使用带有多个参数的列表模式时遇到了问题.例如,尝试定义:
somefunction (x:xs) (y:ys) = x:[y]
Run Code Online (Sandbox Code Playgroud)
结果Occurs check: cannot construct the infinite type: t0 = [t0]
.
基本上,我想将两个列表作为参数添加到函数中,并使用(x:xs)模式匹配方法对它们进行操作.为什么这是错的,我该怎么做呢?非常感谢!
编辑:在答案中需要使用更多代码进行更新.
somefunction a [] = [a]:[]
somefunction [] b = [b]:[]
somefunction (x:xs) (y:ys) = x:[y]
Run Code Online (Sandbox Code Playgroud)
编辑2:错过了一个重要的更新.我用上面的代码得到的错误是Occurs check: cannot construct the infinite type: t0 = [[t0]]
.我想我现在明白了这个问题.
你的功能片段完美无缺:
(! 514)-> ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> let f (x:xs) (y:ys) = x:[y]
Prelude> :type f
f :: [a] -> [a] -> [a]
Run Code Online (Sandbox Code Playgroud)
但是上下文与该类型相矛盾,类型推断会给出错误.例如,我可以创建一个会出现此错误的上下文:
Prelude> let g xs ys = xs : ys
Prelude> :type g
g :: a -> [a] -> [a]
Run Code Online (Sandbox Code Playgroud)
然后,如果我结合f
并g
喜欢下面,那么我得到你的错误:
Prelude> let z x y = g x (f x y)
<interactive>:7:20:
Occurs check: cannot construct the infinite type: a0 = [a0]
In the first argument of `f', namely `x'
In the second argument of `g', namely `(f x y)'
In the expression: g x (f x y)
Prelude>
Run Code Online (Sandbox Code Playgroud)
要正确理解错误,您需要检查(或发布)足够的上下文.