警卫和匿名功能列入清单 [英] Guards and concatiating to lists in an anonymous function
问题描述
这个问题在逻辑上很容易解决。我必须分解一个正整数和负整数的列表,并将它们分组,使得
[1,2,3,-1,-2,-3,1, 2,3]变为[[1,2,3],[ - 1,-2,-3],[1,2,3]]
我会喜欢使用更高阶的函数,foldr可以通过匿名函数来执行两个参数。
这是我目前为止的内容。
split = foldr(\ xy - > if(x> 0)
then if(head(head y) )< 0
then [x]:y
else x:head y --error here
else if(x <0)
then if(head(head ))> 0
then [x]:y
else x:head y
else y
)
[[]]
这是我得到的错误
发生检查:不能解释ct无限类型:a0 = [a0]
在'(:)'的第一个参数中,即`x'
在表达式中:x:head y
在表达式中:
if(head(head y))< 0 then [x]:y else x:head y
我有两个问题。
1)为什么我在第7行得到一个类型错误?
我是不是一个整数(x)到一个2)你如何使用警卫写出条件?我试过这样做,但我一直在'|'
<你只是想保持 tail y
。在
foldr(\ xy - > if(x> 0)
then if(head(head y))<0
then [x]:y
else x:head y
你有 x ::(Num a,Ord a)=> a
, y ::(Num a,Ord a) => [[a]]
和 head y ::(Num a,Ord a)=> [a]
p>
因此,忘记 tail y
会刮掉一层 []
。 else
分支应该是
else(x:head y ):尾部y
在外部 但是,在你的函数之后有两个语义问题。 首先, t处理 I am trying to wrap my head around the syntax of Haskell. This problem is very simple to solve logically. I have to break up a list of positive and negative integers and group them such that [1,2,3,-1,-2,-3,1,2,3] becomes [[1,2,3],[-1,-2,-3], [1,2,3]] I would like to use a higher order function, foldr to be able to do that with an anonymous function taking in two arguements. This is what I have so far. this is the error i get I have two questions. 1) Why am I getting a type error at line 7? Am I not concatenation an integer (x) to a list of integers (head y) 2) How do you write the conditions out using guards? I tried doing it but I kept getting You're simply missing to keep you have So forgetting the in both branches of the outer But, your function has two semantic problems after that. First, you don't treat the case that 这篇关于警卫和匿名功能列入清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!的两个分支中if $ c
头部y
为空的情况,这将在达到列表的末尾时引发异常,其次,它无法在无限列表上工作,因为组合函数不会构造任何东西其第二个参数之前的结果是已知的。如果后者出现问题,您可以在这个答案中找到一个足够懒惰的组合函数 。split = foldr (\ x y -> if (x > 0)
then if (head (head y)) < 0
then [x] : y
else x : head y --error here
else if (x < 0)
then if (head (head y)) > 0
then [x] : y
else x : head y
else y
)
[[]]
Occurs check: cannot construct the infinite type: a0 = [a0]
In the first argument of `(:)', namely `x'
In the expression: x : head y
In the expression:
if (head (head y)) < 0 then [x] : y else x : head y
parsing error at '|'
tail y
. Infoldr (\ x y -> if (x > 0)
then if (head (head y)) < 0
then [x] : y
else x : head y
x :: (Num a, Ord a) => a
, y :: (Num a, Ord a) => [[a]]
, and head y :: (Num a, Ord a) => [a]
.tail y
shaves off one layer of []
. the else
branch should beelse (x:head y) : tail y
if
.head y
is empty, that will cause an exception when the end of the list is reached, and second, it doesn't work on infinite lists, since the combinator function doesn't construct anything of the result before its second argument is known. If the latter is a problem, you can find a sufficiently lazy combinator function in this answer.