Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module EditorBetter where
import Data.Maybe(fromMaybe)
-- A very simple text editor, but more efficient
data Editor = Ed { before :: [Char] -- In reverse order
, cursor :: Maybe Char
, after :: [Char] }
empty :: Editor
empty = Ed [] Nothing []
go_left :: Editor-> Editor
go_left e@(Ed [] _ _) = e
go_left (Ed (a:as) (Just c) bs) = Ed as (Just a) (c: bs)
go_right :: Editor-> Editor
go_right e@(Ed _ _ []) = e
go_right (Ed as (Just c) (b:bs)) = Ed (c:as) (Just b) bs
-- Insert a char to the right of the cursor, move cursor
insert :: Char-> Editor-> Editor
insert t (Ed as Nothing bs) = Ed as (Just t) bs
insert t (Ed as (Just c) bs) = Ed (c:as) (Just t) bs
-- Delete character under the cursor
delete :: Editor-> Editor
delete (Ed as _ (b:bs)) = Ed as (Just b) bs
delete (Ed (a:as) _ []) = Ed as (Just a) []
delete (Ed [] _ []) = Ed [] Nothing []
-- Remove character to the left of cursor
remove :: Editor-> Editor
remove = delete . go_left
-- Insert a string: successively insert characters
insert_str :: String-> Editor-> Editor
insert_str = flip $ foldl (flip insert)
instance Show Editor where
show (Ed as c bs) =
reverse as ++ fromMaybe '?' c:bs ++"\n" ++ replicate (length as) ' ' ++ "^"