简体   繁体   中英

Haskell finding the length of a list from another equation

So I have an equation that returns a list given an 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.

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:

 Int -> [Int] -> Bool

which means that it needs two arguments (of type Int and list of Int s respectively) to return a boolean.

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 .

This function has type [Int] -> Bool and functions do not have a Show instance (~cannot be printed on the screen).

What you probably meant

You don't seem to need getST so you can just use:

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.

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]) -> 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 . 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 getList 3 -- Will be False
con getList 2 -- Will be True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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