在 where 中定义辅助函数
Defining secondary function in where
我有这个可以用
import Data.List
import Data.Maybe
mI l n | l == [] = Nothing
| n == 0 = Just h
| otherwise = mI t (n-1)
where h = head l
t = tail l
然后是这个,它成功地让我从 Just
中得到了一个数字值
myIndex l n
| m == Nothing = error "No list."
| otherwise = fromJust m
where m = mI l n
然而我做不到没有错误
myIndex' l n
| m == Nothing = error "No list."
| otherwise = fromJust m
where m = mI l n | l == [] = Nothing
| n == 0 = Just h
| otherwise = mI t (n-1)
where h = head l
t = tail l
...
error: parse error on input `|'
为什么它不允许我在第二个 where
内定义辅助函数?
您试图将 m
和 mI
的定义塞进一个定义中。
您可能打算这样做:
myIndex' l n
| m == Nothing = error "No list."
| otherwise = fromJust m
where m = mI l n
mI l n | l == [] = Nothing
| n == 0 = Just h
| otherwise = mI t (n-1)
where h = head l
t = tail l
你的线路
where m = mI l n ...
没有意义。您是在定义 m
还是在定义函数 mI
?我想你想要的是:
where m = mI l n
mI l n | l == ...
此外,最好使用模式,例如
mI [] n = Nothing
mI (h:t) n | n == 0 = Just h
| otherwise = mI t (n-1)
我有这个可以用
import Data.List
import Data.Maybe
mI l n | l == [] = Nothing
| n == 0 = Just h
| otherwise = mI t (n-1)
where h = head l
t = tail l
然后是这个,它成功地让我从 Just
myIndex l n
| m == Nothing = error "No list."
| otherwise = fromJust m
where m = mI l n
然而我做不到没有错误
myIndex' l n
| m == Nothing = error "No list."
| otherwise = fromJust m
where m = mI l n | l == [] = Nothing
| n == 0 = Just h
| otherwise = mI t (n-1)
where h = head l
t = tail l
...
error: parse error on input `|'
为什么它不允许我在第二个 where
内定义辅助函数?
您试图将 m
和 mI
的定义塞进一个定义中。
您可能打算这样做:
myIndex' l n
| m == Nothing = error "No list."
| otherwise = fromJust m
where m = mI l n
mI l n | l == [] = Nothing
| n == 0 = Just h
| otherwise = mI t (n-1)
where h = head l
t = tail l
你的线路
where m = mI l n ...
没有意义。您是在定义 m
还是在定义函数 mI
?我想你想要的是:
where m = mI l n
mI l n | l == ...
此外,最好使用模式,例如
mI [] n = Nothing
mI (h:t) n | n == 0 = Just h
| otherwise = mI t (n-1)