简体   繁体   English

Haskell从另一个等式中找到列表的长度

[英]Haskell finding the length of a list from another equation

So I have an equation that returns a list given an int. 因此,我有一个方程式返回给定int的列表。 I want to put that into another equation to see if the length is either of length one or two and return True if it is of length one and False if it is not. 我想将其放入另一个等式中,以查看长度是长度一还是长度二,如果长度为一,则返回True,否则返回False。

con :: Int -> [Int] -> Bool
con getList x
    | length x == 1 = True
    | otherwise     = False

Here's the closest I could get but it throws the error 这是我能得到的最接近的,但是会引发错误

ERROR - Cannot find "show" function for:
*** Expression : con 3
*** Of type    : [Int] -> Bool

The cause of the error 错误原因

The error is caused by the fact that your con has the type: 该错误是由您的con具有以下类型的事实引起的:

 Int -> [Int] -> Bool

which means that it needs two arguments (of type Int and list of Int s respectively) to return a boolean. 这意味着它需要两个参数(分别为Int类型和Int列表)来返回一个布尔值。

Now, the expression con 3 just applies 3 to con (supplying one argument), returning a function that takes a list of Int s and returns Bool . 现在,表达式con 3仅将3应用于con (提供一个参数),返回一个函数,该函数接受一个Int列表并返回Bool

This function has type [Int] -> Bool and functions do not have a Show instance (~cannot be printed on the screen). 此函数的类型为[Int] -> Bool并且这些函数没有Show实例(〜无法在屏幕上打印)。

What you probably meant 你可能是什么意思

You don't seem to need getST so you can just use: 您似乎不需要getST因此可以使用:

con :: [a] -> Bool
con = (== 1) . length

Live demo 现场演示

to have a function that given a list returns a bool so that: if the length of the list is 1 then the return value is True and False otherwise. 具有给定列表的函数将返回布尔值,以便:如果列表的长度为1则返回值为True ,否则为False

If you just want to pass the length of the list, then things get even simpler: 如果您只想传递列表的长度,那么事情会变得更加简单:

con :: Int -> Bool
con = (== 1)

Live demo 现场演示

I agree with the other interpretation that you probably just need a function that works with a list directly but in case you intended for the first argument to con to be a function of type Int -> [Int] , and then you want con to check whether the result of that function, applied to an Int argument, ends up having length 1, then you could do this: 我同意另一种解释,即您可能只需要一个直接用于列表的函数,但是如果您打算让第一个参数con成为Int -> [Int]类型的函数 ,然后您要con检查该函数的结果是否应用到Int参数,是否最终长度为1,那么您可以执行以下操作:

con :: (Int -> [Int]) -> Int -> Bool
con f = (== 1) . length . f

Now suppose you have a different function that produces a list of Int s from a given Int . 现在假设您有一个不同的函数,该函数根据给定的Int生成Int的列表。 Maybe the length of the output is different depending on whether the input is even or odd: 取决于输入是偶数还是奇数,输出的长度可能不同:

getList :: Int -> [Int]
getList x
    | odd x = [x, x, x]
    | otherwise = [x]

Then we can check whether the output will have length 1 or not using con : 然后我们可以使用con来检查输出的长度是否为1:

con getList 3 -- Will be False
con getList 2 -- Will be True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM