Haskell不在范围列表中理解 [英] Haskell not in scope list comprehension

查看:87
本文介绍了Haskell不在范围列表中理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 all_nat x = [ls| sum ls == x]

我想写一个给定整数x的函数,它返回所有他们的元素总和后的结果列表是整数x,但我总是得到错误不在范围内:'ls'。我是哈斯克尔新手。这里的语法错误是什么?

I'd like to write a function that given an integer x it returns all the lists that the result of their elements when summed is the integer x but I always get the error "not in scope: 'ls' " for both times it apperas. I'm new to haskell. What's the syntax error here?

推荐答案

问题是您需要在某处定义所有使用的变量,但 ls 未定义。而且,不能自动定义,因为编译器不知道任务 - 应该如何生成列表?何隆可以吗?积极与否,积分与否?不幸的是,对于现代非AI语言,您对代码的定义非常模糊。
让我们来帮助编译器。为了解决这些问题,涉及一些数学和归纳推理算法通常是有用的。例如,让我们写一个有序列表的算法(其中[2,1]和[1,2]是不同的解决方案):

The problem is that you need to define all used variables somewhere, but ls is undefined. Moreover, it can't be defined automatically, because the compiler doesn't know about the task — how the list should be generated? Ho long can it be? Are terms positive or not, integral or not? Unfortunately your code definition of the problem is quite vague for modern non-AI languages. Let's help the compiler. To solve such problems, it's often useful to involve some math and infer the algorithm inductively. For example, let's write an algorithm with ordered lists (where [2,1] and [1,2] are different solutions):


  1. 从一个基础开始,你知道某些给定输入的输出。例如,对于0,只有一个空的术语列表(如果0可能是一个术语,则任何数字都可以以无限多种方式分解为和)。所以,让我们定义:
  1. Start with a basis, where you know the output for some given input. For example, for 0 there is only an empty list of terms (if 0 could be a term, any number could be decomposed as a sum in infinitely many ways). So, let's define that:



allNats 0 = [[]] --One empty list




  1. 一个归纳步骤。假设我们可以分解一个数字 n ,我们可以通过添加 k 来分解任意数量的 n + k em>作为所有 n 分解的术语。换句话说:对于大于0的数字,我们可以从1到 n 取任意数字 k ,并将它作为( n - k ):

  1. An inductive step. Assuming we can decompose a number n, we can decompose any number n+k for any positive k, by adding k as a term to all decompositions of n. In other words: for numbers greater than 0, we can take any number k from 1 to n, and make it the first term of all decompositions of (n­-k):



allNats n = [ k:rest                   --Add k as a head to the rest, where
            | k <- [1 .. n]            --k is taken from 1 to n, and
            , rest <- allNats (n - k)] --rest is taken from solutions for (n—k)



的解决方案就这些!让我们来测试一下:

That's all! Let's test it:

ghci> allNat 4
[[1,1,1,1],[1,1,2],[1,2,1],[1,3],[2,1,1],[2,2],[3,1],[4]]

这篇关于Haskell不在范围列表中理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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