Sam*_*Sam 0 haskell functional-programming
我想创建一个名为Structured的结构数据类型,可用于表示String,Int和List.例如,结构类似于:[ Int,String,Int,[ Int ]].
问题1:如何创建此数据类型?
data Structured = ...
Run Code Online (Sandbox Code Playgroud)
问题2:一个名为Confirm的函数确认输入满足限制,并且签名类型为confirm :: Restriction - > Structure - > Maybe Bool
data Structured = Structured Int String Int [Int]
Run Code Online (Sandbox Code Playgroud)
会工作.
confirm :: (Structured -> Bool) -> Structured -> Bool
Run Code Online (Sandbox Code Playgroud)
似乎是一个更明智的类型,但有一个简单的实现id.
我不认为你需要Maybe Bool从一个贬值函数返回- Maybe a当你经常重建时有用a,但有时却不会.(这对于非常简单的错误处理是有好处的,例如 - Nothing如果有错误则给出.)在这种情况下,您总是可以得出您的输入是否有效的结论,因此您可以随时回馈True或False- 不需要Maybe.
也许你可能有类似的东西
confirm :: (String -> Bool) -> (Int -> Bool) -> Structured -> Bool
confirm okString okInt (Structured int1 string int2 ints) =
all okInt (int1:int2:ints) && okString string
Run Code Online (Sandbox Code Playgroud)
这里int1:int2:ints是具有列表int1中的前int2面前ints.
定义Structured的更好的方法是:
data Structured = Structured {
length ::Int,
name ::String,
width ::Int,
somenumbers :: [Int]}
Run Code Online (Sandbox Code Playgroud)
那你就有了
confirm :: (String -> Bool) -> (Int -> Bool) -> Structured -> Bool
confirm okString okInt s =
all okInt (length s:width s:somenumbers s) && okString (name s)
Run Code Online (Sandbox Code Playgroud)
它与第一个数据声明完成相同的工作,但为您提供了获取内部结构的功能.