Add maybe/optional example

This commit is contained in:
George Thomas 2026-03-25 01:57:56 +00:00
parent 6ec7bc004f
commit 8f7a1c31f3
3 changed files with 17 additions and 0 deletions

View File

@ -2,6 +2,7 @@ module Main (main) where
import Data.Vector.Storable qualified as V import Data.Vector.Storable qualified as V
import GarnetRs.Wrapped import GarnetRs.Wrapped
import System.IO
main :: IO () main :: IO ()
main = do main = do
@ -13,3 +14,5 @@ main = do
putStrLn $ "3 + 4 = " <> show (add 3 4) putStrLn $ "3 + 4 = " <> show (add 3 4)
putStrLn $ "Tree sum: " <> show (sumTree (Fork (Fork (Leaf 1) (Fork (Leaf 2) (Leaf 3))) (Leaf 4))) putStrLn $ "Tree sum: " <> show (sumTree (Fork (Fork (Leaf 1) (Fork (Leaf 2) (Leaf 3))) (Leaf 4)))
putStrLn $ "Slice sum: " <> show (sumSlice $ V.fromList [0 .. 5]) putStrLn $ "Slice sum: " <> show (sumSlice $ V.fromList [0 .. 5])
putStrLn "Nothing." >> printOptional Nothing
putStr "Something: " >> hFlush stdout >> printOptional (Just 67)

View File

@ -10,6 +10,7 @@ module GarnetRs.Wrapped (
add, add,
sumTree, sumTree,
sumSlice, sumSlice,
printOptional,
) where ) where
import Control.Monad.Cont import Control.Monad.Cont
@ -72,3 +73,8 @@ sumTree = unsafePerformIO . flip withBTree (flip with $ Raw.sum_tree . unsafeFro
sumSlice :: V.Vector Int64 -> Int64 sumSlice :: V.Vector Int64 -> Int64
sumSlice v = unsafePerformIO $ V.unsafeWith v \p -> Raw.sum_slice (unsafeFromPtr p) (fromIntegral $ V.length v) sumSlice v = unsafePerformIO $ V.unsafeWith v \p -> Raw.sum_slice (unsafeFromPtr p) (fromIntegral $ V.length v)
printOptional :: Maybe Int8 -> IO ()
printOptional = \case
Nothing -> Raw.print_optional (unsafeFromPtr nullPtr)
Just t -> with t (Raw.print_optional . unsafeFromPtr)

View File

@ -87,3 +87,11 @@ extern "C" fn sum_tree(t: &BTreeC) -> i64 {
extern "C" fn sum_slice(v: *const i64, s: usize) -> i64 { extern "C" fn sum_slice(v: *const i64, s: usize) -> i64 {
unsafe { slice::from_raw_parts(v, s) }.iter().sum() unsafe { slice::from_raw_parts(v, s) }.iter().sum()
} }
#[unsafe(no_mangle)]
extern "C" fn print_optional(x: Option<&i8>) -> () {
match x {
Some(x) => println!("{}", x / 2),
None => {}
}
}