保护并连接到匿名函数中的列表 [英] Guards and concatiating to lists in an anonymous function

查看:23
本文介绍了保护并连接到匿名函数中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解 Haskell 的语法.

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] 变成 [[1,2,3],[-1,-2,-3], [1,2,3]]

[1,2,3,-1,-2,-3,1,2,3] becomes [[1,2,3],[-1,-2,-3], [1,2,3]]

我想使用一个更高阶的函数 foldr 以便能够通过一个匿名函数来实现这一点,该函数接受两个参数.

I would like to use a higher order function, foldr to be able to do that with an anonymous function taking in two arguements.

这是我目前所拥有的.

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

我有两个问题.

1) 为什么我在第 7 行收到类型错误?

1) Why am I getting a type error at line 7?

我不是将整数 (x) 连接到整数列表 (头 y) 吗

Am I not concatenation an integer (x) to a list of integers (head y)

2) 你如何使用守卫写出条件?我尝试这样做,但我一直在|"处出现 解析错误

2) How do you write the conditions out using guards? I tried doing it but I kept getting parsing error at '|'

推荐答案

您只是缺少保持 tail y.在

foldr (\ 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].

you have x :: (Num a, Ord a) => a, y :: (Num a, Ord a) => [[a]], and head y :: (Num a, Ord a) => [a].

因此,忘记 tail y 会刮掉一层 [].else 分支应该是

So forgetting the tail y shaves off one layer of []. the else branch should be

else (x:head y) : tail y

在外部 if 的两个分支中.

in both branches of the outer if.

但是,你的函数在那之后有两个语义问题.

But, your function has two semantic problems after that.

第一,你不处理head y为空的情况,到达列表末尾会导致异常,第二,对无限列表不起作用,因为在其第二个参数已知之前,组合器函数不会构造任何结果.如果后者是一个问题,你可以在这个答案中找到一个足够懒惰的组合函数.

First, you don't treat the case that 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.

这篇关于保护并连接到匿名函数中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆