Say for example you have
InttoIntList x y
And its Type conversion was
Int -> Int -> [Int]
How would you establish a base case for two inputs to another list type like [Int]
Say for example you have
InttoIntList x y
And its Type conversion was
Int -> Int -> [Int]
How would you establish a base case for two inputs to another list type like [Int]
基本情况不是由函数的类型决定的。是的,通常类型可以给出提示。例如对于列表,基本情况通常是空列表[],但本身不是。
此外,函数采用两个或多个参数是一种常见的误解。在 Haskell 中,每个函数都只接受一个参数。然而,输出可能是一个再次接受参数的函数(这里就是这种情况)。
解决了这两个问题后,问题就出现了,基本情况是什么InttoIntList。好吧,基本案例是不涉及递归的案例。如果我正确理解您的功能,您希望生成一个数字列表,每次从 firstInt到 second递增Int。
因此,基本情况可能是第一个Int大于第二个的情况Int。在这种情况下,我们可能希望返回一个空列表,所以:
intToIntList m n | m > n = [] -- base case
然后递归情况是 when m <= n。在这种情况下,我们通常希望返回一个以 开头m的列表,后跟来自 的列表intToIntList (m+1) n,因此:
| otherwise = m : intToInt (m+1) n
这(:) :: a -> [a] -> [a]是一个列表构造函数。它创建一个带有m头部(第一个元素)和尾部(剩余元素)的列表。intToInt (m+1) n
或将其放在一起:
intToIntList :: Int -> Int -> [Int]
intToIntList m n | m >= n = []
| otherwise = m : intToIntList (m+1) n