Jump to content

Kernighans large earthquake problem: Difference between revisions

m
→‎{{header|AppleScript}}: Quick refactor to handle a missing file and any blank lines.
m (→‎{{header|AppleScript}}: Quick refactor to handle a missing file and any blank lines.)
Line 130:
kernighansEarthquakes(6)</lang>
 
===Functional===
 
Checking that the file exists, and discarding any blank lines,
Or,while emphasising code reuse, (and speed of writing and refactoring):
 
<lang applescript>use AppleScript version "2.4"
Line 138 ⟶ 140:
 
property magnitude : 6.0
property filePathfp : "~/Desktop/data.txt"
 
 
-------------------------- TEST ---------------------------
on run
unlines({("Magnitudes above " & magnitude as string) & ¬
bindLR(readFileLR(fp), ¬
" in " & filePath & ":", ""} & ¬
report(fp, magnitude))
filter(aboveThreshold(magnitude), paragraphs of readFile(filePath)))
end run
 
 
-------------------- EARTHQUAKE REPORT --------------------
 
-- readFilereport :: FilePath -> IOFloat -> String -> String
on report(fp, threshold)
script
seton lst to {}|λ|(s)
unlines({("Magnitudes above " & magnitude as string) & ¬
" in " & filePathfp & ":", ""} & ¬
filter concatMap(aboveThreshold(magnitudethreshold), paragraphs of readFile(filePath)s))
returnend lst|λ|
end script
end report
 
 
Line 152 ⟶ 170:
script
on |λ|(s)
if "" ≠ s and threshold < (item -1 of words of s) as number then
{s}
else
{}
set lng to length ofend xsif
end |λ|
end script
Line 160 ⟶ 182:
-------------------- REUSABLE GENERICS --------------------
 
-- filterLeft :: (a -> Bool)Either -> [a] -> [a]b
on filter|Left|(p, xsx)
{type:"Either", |Left|:x, |Right|:missing value}
tell mReturn(p)
end |Left|
set lst to {}
 
set lng to length of xs
 
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
 
 
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Left| of m then
m
else
mReturn(mf)'s |λ|(|Right| of m)
end if
end bindLR
 
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(pf)
repeat with i from 1 to lng
set vacc to acc & (|λ|(item i of xs, i, xs))
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
return acc
end filter
end concatMap
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
Line 185 ⟶ 229:
end mReturn
 
 
-- readFile :: FilePath -> IO String
-- readFileLR :: FilePath -> Either String IO String
on readFilereadFileLR(strPath)
set ca to current application
set e to reference
Line 194 ⟶ 239:
stringByStandardizingPath) ¬
encoding:(ca's NSUTF8StringEncoding) |error|:(e))
if missing values is emissing value then
s|Left|((localizedDescription of e) as string)
else
|Right|(localizedDescription of e)s as string)
end if
end readFilereadFileLR
 
 
-- unlines :: [String] -> String
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.