Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- less difficult than nil
- null = {}
- -- see haskell
- error_thunk = {}
- --[[
- pattern matches with optional
- else fallback. if no else is
- given and nothing matches, it
- crashes.
- Don't pass nil, except for the
- subject. Use null instead
- everywhere else, or it doesn't
- work correctly.
- When nesting whens, use "_when"
- for all nested whens and only
- "when" for the outer one.
- ]]
- function when(s, ...)
- local result = _when(s,...)
- if(result == error_thunk) then
- -- no match (not exhaustive)
- print("when did not match " ..
- tostring(subject),0,0,8)
- print("result: " ..
- tostring(result))
- print("m:" ..
- tostring(matches))
- for i, v in ipairs(matches) do
- print(tostring(v[1]) ..
- " -> " .. tostring(v[2]))
- end
- local now = t()
- local crashtime = now + 4
- --while(t() < crashtime )do end
- error("when not exhaustive!")
- elseif(result == null) then
- return nil
- end
- return result
- end
- --[[
- Use this for nested whens.
- ]]
- function _when(s, ...)
- local subject = s
- if subject == nil then
- subject = null
- end
- local matches =
- partition({...},2)
- local result = nil
- for _,cond in ipairs(matches)do
- if #cond == 1 and
- result == nil then
- result = cond[1]
- elseif subject == cond[1] and
- result == nil then
- result = cond[2]
- end
- end
- -- match found!
- if result != nil then
- return result
- end
- -- no match
- return error_thunk
- end
Advertisement
Add Comment
Please, Sign In to add comment