【发布时间】:2011-09-05 12:44:46
【问题描述】:
你好,我正在做一些单词搜索程序
例如
当“text.txt”文件包含“foo foos foor .. foo傻瓜”时
然后搜索“foo”
然后只打印数字 2
反复搜索
但我是haskell初学者
我的代码在这里
:module +Text.Regex.Posix
putStrLn "type text file"
filepath <- getLine
data <- readFile filepath
--1. this makes <interactive>:1:1: parse error on input `data' how to fix it?
parsedData =~ "[^- \".,\n]+" :: [[String]]
--2. I want to make function and call it again and again
searchingFunc = do putStrLn "search for ..."
search <- getLine
result <- map (\each -> if each == search then count = count + 1) data
putStrLn result
searchingFunc
}
抱歉,代码非常糟糕
我的开发环境是 Windows XP SP3 WinGhci 1.0.2
对不起,我在几个小时前启动了 haskell
非常感谢您的阅读!
编辑:这里是原始方案代码
谢谢!
#lang scheme/gui
(define count 0)
(define (search str)
(set! count 0)
(map (λ (each) (when (equal? str each) (set! count (+ count 1)))) data)
(send msg set-label (format "~a Found" count)))
(define path (get-file))
(define port (open-input-file path))
(define data '())
(define (loop [line (read-line port)])
(when (not (eof-object? line))
(set! data (append data
(regexp-match* #rx"[^- \".,\n]+" line)))
(loop)))
(loop)
(define (cb-txt t e) (search (send t get-value)))
(define f (new frame% (label "text search") (min-width 300)))
(define txt (new text-field% (label "type here to search") (parent f) (callback (λ (t e) (cb-txt t e)))))
(define msg (new message% (label "0Found ") (parent f)))
(send f show #t)
【问题讨论】:
-
我明白了,您在 REPL 上输入了该代码。 Haskell 不是脚本语言(尽管你可以用它来编写脚本),编写代码的常用方法是将其放入后缀为
.hs的文件中。 -
非常感谢您的建议。还有什么?
-
不要使用
data作为标识符。它是 Haskell 中引入新数据类型的保留字。 -
哦!我知道了。再次感谢你
-
另外一点是,Haskell 中的数据是不可变的。这意味着,像
count = count + 1这样的东西是被禁止的,因为在 Haskell 中重新定义变量的值没有任何意义。
标签: function haskell recursion ghci