保持列表的元素具有某些条件,推断类型不够通用

时间:2017-03-27 14:19:23

标签: haskell

我试图保留一个列表,只列出大于或等于i且小于或等于j的数字,字符,字符串,bool等。我也不想改变我对Int-> Int-> [u] - > [u]的初始定义,一些例子:

  >fromTo 3 7 [1..10]
   [3,4,5,6,7]
   >fromTo 1600 1600 [0..]
   [1599]
   > fromTo (-4) (-3) [False,True]
   []
   >fromTo 12 20 "Haskell"
   ""
   >fromTo (-4) 6 [0, 25..]
   [0,25,50,75,100,125]

这是我出现的内容

fromTo :: Int->Int->[u]->[u]                         
fromTo i j list = filter2 i j (filter (\e1 -> e1>= i) list)     

filter2::Int->Int->[u]->[u]
filter2 y x filteredI = (filter (\e2 -> e2<= x) filteredI)

错误信息是:

- Inferred type is not general enough
*** Expression    : filter2
*** Expected type : Int -> Int -> [a] -> [a]
*** Inferred type : Int -> Int -> [Int] -> [Int]

1 个答案:

答案 0 :(得分:0)

问题是您使用Int进行比较,因此u在这种情况下也必须是Int。或者,您可以使ij更通用。此外,您不需要两次拨打filter。您可以按如下方式实施fromTo

fromTo :: Ord a => a -> a -> [a] -> [a]
fromTo i j = filter (\x -> i <= x && x <= j)

然后

fromTo (-4) 50 [0, 25..100]
[0,25,50]

fromTo 'c' 'x' ['a'..'z']
"cdefghijklmnopqrstuvwx"