如何从列表Haskell的列表中返回列表
基本上,我有一个函数,它通过几个条件检查如何从列表Haskell的列表中返回列表,haskell,Haskell,基本上,我有一个函数,它通过几个条件检查[1..9]的每个排列。另外,我有一个函数检查列表的和是否等于一个数字,还有一个函数对列表进行切片。问题是它返回一个错误无法将类型“Int”与“Char”匹配。它在列表中指出,如果所有条件都为真,则必须返回哪个函数。 以下是代码本身: intSumList :: Int -> [Int] -> Bool intSumList _ [] = True intSumList x (y:ys) | x == s
[1..9]
的每个排列。另外,我有一个函数检查列表的和是否等于一个数字,还有一个函数对列表进行切片。问题是它返回一个错误无法将类型“Int”与“Char”匹配。它在列表中指出,如果所有条件都为真,则必须返回哪个函数。
以下是代码本身:
intSumList :: Int -> [Int] -> Bool
intSumList _ [] = True
intSumList x (y:ys)
| x == sum (y:ys) = True
| otherwise = False
slice :: Int -> Int -> [Int] -> [Int]
slice from to s = take (to - from + 1)(drop from s)
find :: (Int,Int,Int,Int) -> [Int]
find (x,z,y,s) = checkPerm (x,z,y,s) l
where
l = L.permutations [1..9]
checkPerm (_,_,_,_ ) [] = ""
checkPerm (x,z,y,s) (p:pz)
| intSumList x (slice 1 5 p) && intSumList z (slice 2 6 p) &&
intSumList y (slice 4 8 p) && intSumList s (slice 5 9 p) = p
| otherwise = permutations (x,z,y,s) pz
当前的问题是,checkPerm
在将空列表作为其第二个参数时返回类型为[Char]
的空列表,而不是[Int]
然而,checkPerm
基本上是在重新实现Data.List.find
import qualified Data.List as DL
import Data.Maybe
import Control.Monad
find :: (Int,Int,Int,Int) -> [Int]
find (x,z,y,s) = fromMaybe [] (DL.find p l)
where makePred x lo hi p = intSumList x (slice lo hi p)
p1 = makePred x 1 5
p2 = makePred z 2 6
p3 = makePred y 4 8
p4 = makePred s 5 9
p = liftM4 (&&) p1 p2 p3 p4
l = DL.permutations [1..9]
DL.find
如果找不到匹配项,则返回Nothing
,或者对于匹配列表只返回l
fromMaybe
将此值转换为空列表或找到的列表。您可以考虑将返回值<代码>查找< /代码>作为<代码> [INT]< /Cord>。<>代码> CuthPurm < /代码>必须有一个返回类型的<代码> [INT]< /Cord>,为什么您要说<代码> CuffPm()=“”< /C>(类型<代码> [char ]< /代码>)?另外,您确实希望<代码> INSUMLISTA[]/COD>是真的吗?空列表的总和通常被认为是0,并且无论如何,您都不会在空列表上实际调用intSumList
;只需使用intsumlistxy=x==sumy
。