monadt_with_IO/Main.lean
2024-06-05 15:49:21 +09:00

62 lines
1.5 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import «MonadtSample»
def ret1 : Except String Nat := .ok 10
def ret2 : Except String Nat := .error "message"
def rets : List (Except String Nat) := [.ok 1, .ok 10, .error "problem 1", .error "problem 2", .ok 100000]
def liftIO (t : ExceptT String Id α) : IO α := do
match t with
| .ok r => EStateM.Result.ok r
| .error s => EStateM.Result.error s
instance : MonadLift (ExceptT String Id) IO where
monadLift := liftIO
def main : IO Unit := do
let fmt := Std.Format.nest 5 <| ".aa gjeoi".toFormat.append ((Std.Format.align true).append ("a".toFormat.append (Std.Format.line.append "b".toFormat)))
IO.println fmt
-- let ret ← ret2
-- IO.println s!"ret: {ret}"
-- let ret ← ret1
-- IO.println s!"ret: {ret}"
try
let ret ← ret1
IO.println s!"ret1: {ret}"
for val in rets do
IO.println s!"ret: {val}"
catch e =>
IO.eprintln s!"Error: {e}"
#eval main
#print main
#eval (1.2).mul 100 |>.round |>.div 100 |>.toString |>.toFormat |>.tag 10
#print Task
def hoge := main.asTask
#check -42.0
#eval 10. * 10^3
#check 10^3
#eval (10.8).toUInt64
#check Float.ofScientific
#eval Float.ofScientific 323 true 1
namespace Float
def sprintf_1 (x : Float) (a : Nat) : String :=
let sign : Bool := x > 0
let up := (if sign then x.toUInt64 else (-x).toUInt64) |>.toNat
let down := (x - up.toFloat) * (10^a).toFloat |>.round |>.toUInt64 |>.toNat
let sign_sign := if sign then "" else "-"
s!"{sign_sign}{up}.{down}"
end Float
#eval (3.14).sprintf_1 0
#eval (3.14).sprintf_1 1
#eval (3.14).sprintf_1 2